1. 程式人生 > >C++學習,實驗四

C++學習,實驗四

con .cpp input pub lose lse put img run

一,draw()函數

技術分享圖片
void graph::draw() {
    int i,j;
    for(i=1;i<=size;i++)
    {
        for(j=1;j<=size-i;j++)
        {
            cout<<" ";
            
        }
        for(j=1;j<=2*i-1;j++)
        {
            cout<<symbol;
        }
        for(j=1;j<=size-i;j++)
        {
            cout
<<" "; } cout<<endl; }
draw()函數

實驗截圖

技術分享圖片

程序運行環境: DevC++5.10

二,fraction函數

技術分享圖片
class Fraction{
    public:
        Fraction();
        Fraction(int a);
        Fraction(int a,int b);
        void show();
        void add(Fraction &f);
        void sub(Fraction &f);
        
void mul(Fraction &f); void div(Fraction &f); int compare(Fraction &f); private: int top; int bottom; };
fraction.h 技術分享圖片
#include<iostream>
#include"fraction.h"
using namespace std;
Fraction::Fraction()
{
    top=0;
    bottom=1;
}
Fraction::Fraction(
int a) { top=a; bottom=1; } Fraction::Fraction(int a,int b) { top=a; bottom=b; } void Fraction::add(Fraction &f) { top=f.top*bottom+top*f.bottom; bottom=bottom*f.bottom; show(); } void Fraction::sub(Fraction &f) { top=top*f.bottom-f.top*bottom; bottom=bottom*f.bottom; show(); } void Fraction::mul(Fraction &f) { top=top*f.top; bottom=bottom*f.bottom; show(); } void Fraction::div(Fraction &f) { top=top*f.bottom; bottom=bottom*f.top; show(); } int Fraction::compare(Fraction &f) { int a,b; a=top*f.bottom-f.top*bottom; if(a>0) { b=1; } else if(a=0) { b=2; } else { b=3; } switch(b) { case 1: cout<<top<<"/"<<bottom<<">"<<f.top<<"/"<<f.bottom; break; case 2: cout<<top<<"/"<<bottom<<"="<<f.top<<"/"<<f.bottom; break; case 3: cout<<top<<"/"<<bottom<<"<"<<f.top<<"/"<<f.bottom; break; default: cout<<"number of b is wrong"; } } void Fraction::show() { cout<<top<<"/"<<bottom<<endl; }
fraction.cpp 技術分享圖片
#include <iostream>
#include"fraction.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main() 
{
    Fraction a;
    Fraction b1(3,4);
    Fraction c(5);
    Fraction d(5,6);
    Fraction b2(3,4);
    Fraction b3(3,4);
    Fraction b4(3,4);
    Fraction b5(3,4);
    a.show();
    b1.show();
    c.show();
    b1.add(d);
    b2.sub(d);
    b3.mul(d);
    b4.div(d);
    b5.compare(d);
    return 0;
}
main.cpp

運行截圖

技術分享圖片

程序運行環境: DevC++5.10

C++學習,實驗四