#include
using namespace std;
class fraction
{
int x;
int y;
public:
fraction operator +(fraction&);
void set(int a,int b)
{x=a;
y=b;
}
void display()
{if(x%y==0)cout<<x/y<<endl;
else if(y%x==0)cout<<"1"<<" "<<y/x<<endl;
else
{ int c;
c=x<y?x:y;
int f;
for(int i=1;i<c;i++)
{if(x%i==0&&y%i==0)
f=i;}
cout<<x/f<<" "<<y/f<<endl;}}};
fraction fraction::operator +(fraction &p1)
{fraction p;
p.x=x*p1.y+p1.x*y;
p.y=y*p1.y;
return p;
}
int main()
{int c,d,e,f;
fraction p,p1,p2;
cin>>c>>d>>e>>f;
p1.set(c,d);
p2.set(e,f);
p=p1+p2;
p.display();
return 0;
}
既然你没把题目贴出来 。我说说如果让我做 应该考虑的点。
一:两个分数的正负之分
二:最终的结果是否需要约分。
http://www.cnblogs.com/pmer/p/3484933.html
#include
#include
using namespace std;
class Fen
{
public:
Fen()
{
zi=0,mu=0;
}
Fen(int z,int m):zi(z),mu(m) {}
void getdate()
{
cin>>zi>>mu;
}
friend Fen operator + (Fen f1,Fen f2);
friend Fen operator - (Fen f1,Fen f2);
friend Fen operator * (Fen f1,Fen f2);
friend Fen operator / (Fen f1,Fen f2);
friend void yu(Fen *f1,Fen *f2);
friend void yu(Fen *f3);
friend ostream& operator<<(ostream&,Fen&);
friend void pan(Fen f4);
private:
int mu,zi;
};
void yu(Fen *f1,Fen *f2)
{
int a,b;
if(f1->mumu)
{
a=f1->mu;
b=f2->mu;
}
else
{
a=f2->mu;
b=f1->mu;
}
int c=b%a;
for(; c!=0;)
{
b=a;
a=c;
c=b%a;
}
int t1,t2;
t1=f2->mu/a;
t2=f1->mu/a;
f1->mu=f1->mu*t1;
f2->mu=f2->mu*t2;
f1->zi=f1->zi*t1;
f2->zi=f2->zi*t2;
}
void yu(Fen *f3)
{
if(f3->zi!=0)
{
int a,b;
if(f3->mu>f3->zi)
{
b=f3->mu;
a=f3->zi;
}
else
{
a=f3->mu;
b=f3->zi;
}
int c=b%a;
for(; c!=0;)
{
b=a;
a=c;
c=b%a;
}
f3->mu=f3->mu/a;
f3->zi=f3->zi/a;
}
else
{
f3->zi=0;
f3->mu=0;
}
}
Fen operator + (Fen f1,Fen f2)
{
return(Fen(f1.zi+f2.zi,f1.mu));
}
Fen operator - (Fen f1,Fen f2)
{
return(Fen(f1.zi-f2.zi,f1.mu));
}
Fen operator * (Fen f1,Fen f2)
{
return(Fen(f1.zi*f2.zi,f1.mu*f2.mu));
}
Fen operator / (Fen f1,Fen f2)
{
return(Fen(f1.zi*f2.mu,f1.mu*f2.zi));
}
ostream& operator<<(ostream& output,Fen& f1)
{
if(f1.zi!=0)
{
if(f1.mu==1||f1.mu==-1)
output<<f1.zi/f1.mu;
else
{
if(f1.mu*f1.zi<0)
output<<"-"<<abs(f1.zi)<<"/"<<abs(f1.mu);
else
output<<f1.zi<<"/"<<f1.mu;
}
}
else
cout<<"0";
}
void pan(Fen f4)
{
if(f4.zi==0)
cout<<"两个分数相等!"<<endl;
else
cout<<"两个分数不相等!"<<endl;
}
int main()
{
Fen f1,f2,f3,f4,f5,f6;
cout<<"请输入第一个分数:"<<endl;
f1.getdate();
cout<<"请输入第二个分数:"<<endl;
f2.getdate();
yu(&f1,&f2);
f3=f1+f2;
yu(&f3);
f4=f1-f2;
yu(&f4);
f5=f1*f2;
yu(&f5);
f6=f1/f2;
yu(&f6);
cout<<"加法结果:"<<endl<<f3<<endl;
cout<<"减法结果:"<<endl<<f4<<endl;
cout<<"乘法结果:"<<endl<<f5<<endl;
cout<<"除法结果:"<<endl<<f6<<endl;
pan(f4);
}