Problem B: 分数类的四则运算【C++】
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 652 Solved: 162
[ Submit][ Status][ Web Board]
Description
编写分数类Fraction,实现两个分数的加、减、乘和除四则运算。主函数已给定。
Input
每行四个数,分别表示两个分数的分子和分母,以0 0 0 0 表示结束。
Output
空格分隔的两个分数的减和除的结果。
Sample Input
1 2 -1 2
4 3 3 4
0 0 0 0
Sample Output
1 -1
7/12 16/9
HINT
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>
#include<cmath>
using namespace std;
class Fraction
{
private:
int nume; // 分子
int deno; // 分母
public:
int flag;
Fraction(int nu=0,int de=1); //构造函数,初始化用
void set(int nu=0,int de=1); //置值,改变值时用
void simplify(); //化简(使分子分母没有公因子)
void output();
Fraction operator + (const Fraction &c2);
Fraction operator - (const Fraction &c2);
Fraction operator * (const Fraction &c2);
Fraction operator / (const Fraction &c2);
bool operator == (int x);
friend istream& operator>>(istream&input,Fraction &c);
};
int gys(int a,int b)
{
return (a%b!=0?(gys(b,a%b)):b);
}
int gbs(int u,int v)
{
int h;
h=gys(u,v);
return (u*v/h);
}
Fraction::Fraction(int nu,int de)
{
if(de!=0)
{
nume=nu;
deno=de;
}
}
void Fraction::set(int nu,int de)//置值,改变值时用
{
if(de!=0)
{
nume=nu;
deno=de;
}
}
Fraction Fraction::operator + (const Fraction &c2)
{
Fraction c;
int r;
if (deno!=c.deno) //取分母的最大公倍数
{
r=gbs(deno,c2.deno);
c.nume=(nume*r/deno)+(c2.nume*r/c2.deno);
c.deno=r;
}
else
{
c.nume=nume+c2.nume;
c.deno=deno;
}
return c;
}
Fraction Fraction::operator - (const Fraction &c2)
{
Fraction c;
int r;
if (deno!=c.deno) //取分母的最大公倍数
{
r=gbs(deno,c2.deno);
c.nume=(nume*r/deno)-(c2.nume*r/c2.deno);
c.deno=r;
}
else
{
c.nume=nume-c2.nume;
c.deno=deno;
}
return c;
}
Fraction Fraction::operator * (const Fraction &c2)
{
Fraction c;
c.nume=nume*c2.nume;
c.deno=deno*c2.deno;
return c;
}
Fraction Fraction::operator / (const Fraction &c2)
{
Fraction c;
c.nume=nume*c2.deno;
c.deno=deno*c2.nume;
return c;
}
bool Fraction::operator == (int x)
{
return !((nume>x)||(nume<x));
}
void Fraction::simplify()//化简(使分子分母没有公因子)
{
int r;
r=gys(nume,deno);
nume/=r;
deno/=r;
}
//流插入
istream& operator>>(istream&input,Fraction &c)
{
int a,b;
input>>a>>b;
c.nume=a;
c.deno=b;
return input;
}
void Fraction::output()
{
simplify();
if(deno!=1)
{
if(nume<0||deno<0)
cout<<"-"<<fabs(nume)<<"/"<<fabs(deno);
else
cout<<nume<<"/"<<deno;
}
else
cout<<nume;
}
//下面用main()函数测试,完成输入输出
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;
}