一个有关分数类的程序,运行结果不正确,请指教!
#include<iostream>using namespace std;
class Fenshu
{
public:
Fenshu(){}
Fenshu(int,int);
int gcd();
Fenshu operator+(Fenshu c);
Fenshu operator-(Fenshu c);
Fenshu operator*(Fenshu c);
Fenshu operator/(Fenshu c);
void display(){cout<<fenzi<<"/"<<fenmu<<endl;}
private:
int fenzi,fenmu;
};
Fenshu::Fenshu(int myfenzi,int myfenmu)
{
fenzi=myfenzi;
fenmu=myfenmu;
}
int Fenshu::gcd()
{
if(0 == fenzi)
{
return fenmu;
}
if( 0 == fenmu)
{
return fenzi;
}
if(fenmu > fenzi)
{
int c = fenzi;
fenzi = fenmu;
fenmu= c;
}
int t;
for(t = fenzi% fenmu ; t > 0 ; t = fenzi % fenmu)
{
fenzi = fenmu;
fenmu = t;
}
return fenmu;
}
Fenshu Fenshu::operator +(Fenshu c)
{
Fenshu temp;
temp.fenzi=fenzi*c.fenmu+c.fenzi*fenmu;
temp.fenmu=fenmu*c.fenmu;
temp.fenzi=temp.fenzi/temp.gcd();
temp.fenmu=temp.fenmu/temp.gcd();
return temp;
}
Fenshu Fenshu::operator-(Fenshu c)
{
Fenshu temp;
temp.fenzi=c.fenzi*fenmu-c.fenmu*fenzi;
temp.fenmu=c.fenmu*fenmu;
temp.fenzi=temp.fenzi/(temp.gcd());
temp.fenmu=temp.fenmu/(temp.gcd());
return temp;
}
Fenshu Fenshu::operator *(Fenshu c)
{
Fenshu temp;
temp.fenzi=fenzi*c.fenzi;
temp.fenmu=fenmu*c.fenmu;
temp.fenzi=temp.fenzi/(temp.gcd());
temp.fenmu=temp.fenmu/(temp.gcd());
return temp;
}
Fenshu Fenshu::operator /(Fenshu c)
{
Fenshu temp;
if(temp.fenmu!=0&&c.fenmu!=0)
temp.fenzi=fenzi*c.fenmu;
temp.fenmu=fenmu*c.fenzi;
temp.fenzi=temp.fenzi/(temp.gcd());
temp.fenmu=temp.fenmu/(temp.gcd());
return temp;
}
int main()
{
Fenshu c1(2,20),c2(3,30);
Fenshu c;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
c=c1+c2;
cout<<"c1+c2=";
c.display();
c=c1-c2;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
c=c1-c2;
cout<<"c1-c2=";
c.display();
c=c1*c2;
cout<<"c1*c2=";
c.display();
return 0;
}