第八周(项目三2)——分数类中的运算符重载。

来源:互联网 发布:淘宝兑换型优惠券 编辑:程序博客网 时间:2024/05/16 01:29
/**烟台大学计算机学院学生*All right reserved.*文件名称*烟台大学计算机学院学生*All right reserved.*文件名称:分数类中的运算符重载(2)*作者:王洪海*完成日期:2013年4月20日*版本号:v1.0*对任务及求解方法的描述部分:分数类中的运算符重载(2)*我的程序:*/#include<iostream>using namespace std;class CF{private:    int nume;  // 分子    int deno;  // 分母public:    CF (int nu=0,int de=1);    void set(int nu,int de);    //置值,改变值时用    void simplify();     //化简(使分子分母没有公因子)    void output();   //输出:以8/6为例,style为0时,原样输出8/6;    CF operator+  (int a);    CF operator-  (int a);    CF operator*  (int a);    CF operator/  (int a);    friend CF operator+  (int a,CF &t);    friend CF operator-  (int a,CF &t);    friend CF operator*  (int a,CF &t);    friend CF operator/  (int a,CF &t);};CF::CF(int nu,int de){    nume=nu;    deno=de;}void CF::set(int nu,int de){nume=nu;deno=de;}void CF::simplify(){int i;int p;if(nume>deno)p=deno;elsep=nume;for(i=2;i<=p;i++){if(nume%i==0&&deno%i==0){nume/=i;deno/=i;}}}void CF::output(){cout<<nume<<"/"<<deno<<endl;}CF CF::operator+  (int a)    {        CF t3;        int n;        n=a*deno;        t3.nume=n+nume;        t3.deno=deno;        return t3;    }CF CF::operator-  (int a)    {        CF t3;        int n,m;        m=deno;        n=a*deno;        t3.deno=deno;        t3.nume=nume-n;        return t3;    }CF CF::operator* (int a)    {        CF t3;        t3.nume=nume*a;        t3.deno=deno;        return t3;    }CF CF::operator/(int a)    {        CF t3;        t3.deno=deno*a;        t3.nume=nume;        return t3;    }CF operator+  (int a,CF &t){        CF t3;        int n;        n=a*t.deno;        t3.nume=n+t.nume;        t3.deno=t.deno;        return t3;}CF operator-  (int a,CF &t){        CF t3;        int n,m;        m=t.deno;        n=a*t.deno;        t3.deno=t.deno;        t3.nume=n-t.nume;        return t3;}CF operator*  (int a,CF &t){        CF t3;        t3.nume=t.nume*a;        t3.deno=t.deno;        return t3;}CF operator/  (int a,CF &t){        CF t3;        t3.deno=t.nume;        t3.nume=a*t.deno;        return t3;}int main() {    CF t1(2,3),t;    int t2=3;    cout<<"原本两个数分别为:"<<endl;    t1.output();    cout<<t2;    cout<<endl;    cout<<"两个数相加得: ";    t=t1+t2;    t.simplify();    t.output();    cout<<"两个数相减得: ";    t=t2-t1;    t.simplify();    t.output();    cout<<"两个数相乘得: ";    t=t2*t1;    t.simplify();    t.output();    cout<<"两个数相除得: ";    t=t1/t2;    t.simplify();    t.output();     return 0;}

运行结果,如下图:


0 0
原创粉丝点击