# 分数类的四则运算【C++】

``````1 2 -1 2
4 3 3 4
0 0 0 0``````

``````1 -1
7/12 16/9
``````

``````#include <iostream>
using namespace std;
int cishu=1;
class Fraction
{
public:
Fraction(){fenzi=0;fenmu=0;}
Fraction(int x,int y){fenzi=x;fenmu=y;}
Fraction operator - (Fraction &k2);
friend istream & operator >>(istream &,Fraction&);
Fraction operator / (Fraction &k1);
friend bool operator == (Fraction &k1,int no);
void output();
private:
int fenzi;
int fenmu;

};

istream & operator >>(istream &input,Fraction&k)
{
input>>k.fenzi>>k.fenmu;
return input;
}

bool operator == (Fraction &k1,int no)
{
if(k1.fenzi==no&&k1.fenmu==no)
return true;
else
return false;
}

Fraction Fraction::operator-(Fraction &k2)
{
return Fraction(fenzi*k2.fenmu-k2.fenzi*fenmu,fenmu*k2.fenmu);
}

Fraction Fraction::operator / (Fraction &k1)
{
return Fraction(fenzi*k1.fenmu,fenmu*k1.fenzi);
}

void Fraction::output()
{
int t,r,u,v;
u=fenmu;
v=fenzi;
if(v>u){t=u;u=v;v=t;}
while((r=u%v)!=0)
{
u=v;
v=r;
}
fenzi/=v;
fenmu/=v;
if(fenmu<0)
{
fenzi=0-fenzi;
fenmu=0-fenmu;
}
if(fenmu==-1)
cout<<0-fenzi;
else if(fenmu==1)
cout<<fenzi;
else
cout<<fenzi<<"/"<<fenmu;
if(cishu%2!=0)
cout<<" ";
cishu+=1;

}
int main()
{
Fraction f1,f2,f3;
while(cin>>f1>>f2)
{
if(f1==0&&f2==0)
break;
f3=f1-f2;
f3.output();
f3=f1/f2;
f3.output();
cout<<endl;
}
return 0;
}
``````

``````#include <iostream>
using namespace std;
int cishu=1;
class Fraction
{
public:
Fraction(){fenzi=0;fenmu=0;}
Fraction(int x,int y){fenzi=x;fenmu=y;}
Fraction operator - (Fraction &k2);
friend istream & operator >>(istream &,Fraction&);
Fraction operator / (Fraction &k1);
friend bool operator == (Fraction &k1,int no);
void output();
private:
int fenzi;
int fenmu;

};

istream & operator >>(istream &input,Fraction&k)
{
input>>k.fenzi>>k.fenmu;
return input;
}

bool operator == (Fraction &k1,int no)
{
if(k1.fenzi==no&&k1.fenmu==no)
return true;
else
return false;
}

Fraction Fraction::operator-(Fraction &k2)
{
return Fraction(fenzi*k2.fenmu-k2.fenzi*fenmu,fenmu*k2.fenmu);
}

Fraction Fraction::operator / (Fraction &k1)
{
return Fraction(fenzi*k1.fenmu,fenmu*k1.fenzi);
}

void Fraction::output()
{
int t,r,u,v;
u=fenmu;
v=fenzi;
if(v>u){t=u;u=v;v=t;}
while((r=u%v)!=0)
{
u=v;
v=r;
}
fenzi/=v;
fenmu/=v;
if(fenmu<0)
{
fenzi=0-fenzi;
fenmu=0-fenmu;
}
if(fenmu==-1)
cout<<0-fenzi;
else if(fenmu==1)
cout<<fenzi;
else
cout<<fenzi<<"/"<<fenmu;
if(cishu%2!=0)
cout<<" ";
cishu+=1;

}
int main()
{
Fraction f1,f2,f3;
while(cin>>f1>>f2)
{
if(f1==0&&f2==0)
break;
f3=f1-f2;
f3.output();
f3=f1/f2;
f3.output();
cout<<endl;
}
return 0;
}
``````