问题:
//Description
//编写分数类Fraction,实现两个分数的加、减、乘和除四则运算。主函数已给定。
//Input
//每行四个数,分别表示两个分数的分子和分母,以0 0 0 0 表示结束。
//Output
//空格分隔的两个分数的减和除的结果。
程序:
#include <iostream>
using namespace std;
class Fraction
{
private:
int nume; // 分子
int deno; // 分母
public:
Fraction(int n=0,int d=0);
friend int tong(Fraction c1,Fraction c2); //友元函数
friend void hua(int *de,int *nu); //为了保留计算所得值,用指针
//构造函数及运算符重载的函数声明
Fraction operator+(Fraction &c);
Fraction operator-(Fraction &c);
Fraction operator*(Fraction &c);
Fraction operator/(Fraction &c);
bool operator==(int n);
friend istream&operator>>(istream&,Fraction&);
void output();
};
int tong(Fraction c1,Fraction c2) //通分
{
int t[8]={2,3,5,7,11,13,17,19},de1=c1.deno,de2=c2.deno,g=1;
for(int i=0;i<8;i++)
{
while(de1%t[i]==0&&de2%t[i]==0)
{
de1/=t[i];
de2/=t[i];
g*=t[i];
}
}
g*=(de1*de2);
if(g<0)
{
g=-g; //如果分数是负数
}
return g;
}
void hua(int *de,int *nu)
{
int t[8]={2,3,5,7,11,13,17,19};
for(int i=0;i<8;i++)
{
while(*de%t[i]==0&&*nu%t[i]==0)
{
*de/=t[i];
*nu/=t[i];
}
}
}
void Fraction::output()
{
if(nume==deno||nume==-deno)
{
cout<<(nume/deno);
}
else if(deno<0)
{
nume=-nume;deno=-deno;
cout<<nume<<"/"<<deno;
}
else if(nume==0)
{
cout<<nume;
}
else
{
cout<<nume<<"/"<<deno;
}
}
Fraction::Fraction(int n,int d)
{
nume=n;
deno=d;
}
Fraction Fraction::operator+(Fraction &c)
{
int g,n;
g=tong(*this,c);
n=nume*(g/deno)+c.nume*(g/c.deno);
hua(&g,&n);
return Fraction(n,g); //直接返回对象并赋值
}
Fraction Fraction::operator-(Fraction &c)
{
int g,n;
g=tong(*this,c);
n=nume*(g/deno)-c.nume*(g/c.deno);
hua(&g,&n);
return Fraction(n,g);
}
Fraction Fraction::operator*(Fraction &c)
{
int d,n;
d=deno*c.deno;
n=nume*c.nume;
hua(&d,&n);
return Fraction(n,d);
}
Fraction Fraction::operator/(Fraction &c)
{
Fraction c1;
int n;
c1=c;
n=c1.deno;
c1.deno=c1.nume;
c1.nume=n;
return (*this)*c1;
}
bool Fraction::operator == (int n)
{
bool g=false;
if(nume==n)
{
g=true;
}
return g;
}
istream&operator>>(istream&input,Fraction&c)
{
input>>c.nume>>c.deno;
return input;
}
int main()
{
Fraction f1,f2,f3;
while(cin>>f1>>f2)
{
if(f1==0&&f2==0)
break;
f3=f1-f2;
f3.output();
cout<<" ";
f3=f1/f2;
f3.output();
cout<<endl;
}
return 0;
}
结果: