C++学习,实验四

一,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++了解还是不够深入,需要更进一步的学习,在实验中,发现了很多以前没注意到的问题,和小细节。

例如: 在函数的实现这一块,可以直接写 show();来表示输出。

在c++中“<”和“>”和其他运算符,仅可以用于四大基本类型,而3/4与5/6之间的大小关系,是认为两个除法表达式之间的大小关系。

show()函数一定要记得实现,不然会出错。

class Fraction() 首字母大写是习惯,小写也没错,但是最好遵循习惯。

posted @ 2018-04-22 22:22  丿罗小黑  阅读(128)  评论(3编辑  收藏  举报