当前位置 : 主页 > 手机开发 > harmonyos >

第8周项目3-分数类中的运算符重载

来源:互联网 收集:自由互联 发布时间:2023-08-29
问题描述: 实现分数类中的运算符重载,在分数类中可以完成分数的加减乘除(运算后再化简)、比较(6种关系)的运算。 代码: #include iostream#include cmathusing namespace std;class CFractio


问题描述:

实现分数类中的运算符重载,在分数类中可以完成分数的加减乘除(运算后再化简)、比较(6种关系)的运算。

代码:

#include <iostream>
#include <cmath>
using namespace std;

class CFraction
{
private:
    int nume;
    int deno;
public:
    CFraction(int n=0,int d=1):nume(n),deno(d){};
    void display();
    void simplify();
    CFraction operator+(CFraction &c2);
    CFraction operator-(CFraction &c2);
    CFraction operator*(CFraction &c2);
    CFraction operator/(CFraction &c2);
    bool operator>(CFraction &c2);
    bool operator<(CFraction &c2);
    bool operator==(CFraction &c2);
    bool operator!=(CFraction &c2);
    bool operator>=(CFraction &c2);
    bool operator<=(CFraction &c2);
};
void CFraction::display()
{
    cout<<nume<<"/"<<deno;
}
void CFraction::simplify()
{
    int m,d,r;
    m=abs(nume);
    d=abs(deno);
    while((r=(m%d)))
    {
        m=d;d=r;
    }
    nume/=d;deno/=d;
}
CFraction CFraction::operator+(CFraction &c2)
{
    CFraction c;
    c.nume=nume*c2.deno+c2.nume*deno;
    c.deno=deno*c2.deno;
    c.simplify();
    return c;
}
CFraction CFraction::operator-(CFraction &c2)
{
    CFraction c;
    c.nume=nume*c2.deno-c2.nume*deno;
    c.deno=deno*c2.deno;
    c.simplify();
    return c;
}
CFraction CFraction::operator*(CFraction &c2)
{
    CFraction c;
    c.nume=nume*c2.nume;
    c.deno=deno*c2.deno;
    c.simplify();
    return c;
}
CFraction CFraction::operator/(CFraction &c2)
{
    CFraction c;
    c.nume=nume*c2.deno;
    c.deno=deno*c2.nume;
    c.simplify();
    return c;
}
bool CFraction::operator>(CFraction &c2)
{
    if(nume*c2.deno>c2.nume*deno)
        return true;
    return false;
}
bool CFraction::operator<(CFraction &c2)
{
    if(nume*c2.deno<c2.nume*deno)
        return true;
    return false;
}
bool CFraction::operator==(CFraction &c2)
{
    if(nume*c2.deno==c2.nume*deno)
        return true;
    return false;
}
bool CFraction::operator>=(CFraction &c2)
{
    return !((*this)<c2);
}
bool CFraction::operator<=(CFraction &c2)
{
    return !((*this)>c2);
}
bool CFraction::operator!=(CFraction &c2)
{
    return !((*this)==c2);
}
int main()
{
    CFraction c1(6,8),c2(4,5),c;
    cout<<"c1=";
    c1.display();
    cout<<endl;
    cout<<"c2=";
    c2.display();
    cout<<endl;
    c=c1+c2;
    cout<<"c1+c2=";
    c.display();
    c=c1-c2;
    cout<<endl;
    cout<<"c1-c2=";
    c.display();
    cout<<endl;
    c=c1*c2;
    cout<<"c1*c2=";
    c.display();
    cout<<endl;
    c=c1/c2;
    cout<<"c1/c2=";
    c.display();
    cout<<endl;
    if(c1>c2) cout<<"c1>c2"<<endl;
    if(c1<c2) cout<<"c1<c2"<<endl;
    if(c1==c2) cout<<"c1==c2"<<endl;
    if(c1>=c2) cout<<"c1>=c2"<<endl;
    if(c1<=c2) cout<<"c1<=c2"<<endl;
    if(c1!=c2) cout<<"c1!=c2"<<endl;
    return 0;
}

 

运行结果:

第8周项目3-分数类中的运算符重载_#include

上一篇:第14周项目1-小玩文件(2)
下一篇:没有了
网友评论