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;
}
1 #include <iostream.h> 2 int cishu=1; 3 class Fraction 4 {public: 5 Fraction(){a=0;b=0;} 6 Fraction(int x,int y){a=x;b=y;} 7 Fraction operator - (Fraction &k); 8 Fraction operator + (Fraction &k); 9 Fraction operator * (Fraction &k); 10 Fraction operator / (Fraction &k); 11 friend istream & operator >>(istream &,Fraction&); 12 friend bool operator == (Fraction &k1,int no); 13 void output(); 14 private: 15 int a; 16 int b; 17 }; 18 istream & operator >>(istream &in,Fraction&k) 19 { 20 in>>k.a>>k.b; 21 return in; 22 } 23 bool operator == (Fraction &k1,int no) 24 { 25 if(k1.a==no&&k1.b==no) 26 return true; 27 else 28 return false; 29 } 30 31 Fraction Fraction::operator - (Fraction &k) 32 { 33 return Fraction(a*k.b-k.a*b,b*k.b); 34 } 35 36 Fraction Fraction::operator + (Fraction &k) 37 { 38 return Fraction(a*k.b+k.a*b,b*k.b); 39 } 40 41 Fraction Fraction::operator * (Fraction &k) 42 { 43 return Fraction(a*k.a,b*k.b); 44 } 45 46 Fraction Fraction::operator / (Fraction &k) 47 { 48 return Fraction(a*k.b,b*k.a); 49 } 50 51 void Fraction::output() 52 { 53 int t,r,u,v; 54 u=b; 55 v=a; 56 if(v>u){t=u;u=v;v=t;} 57 while((r=u%v)!=0) 58 { 59 u=v; 60 v=r; 61 } 62 a/=v; 63 b/=v; 64 if(b<0) 65 { 66 a=0-a; 67 b=0-b; 68 } 69 if(b==-1) 70 cout<<0-a; 71 else if(b==1) 72 cout<<a; 73 else 74 cout<<a<<"/"<<b; 75 if(cishu%2!=0) 76 cout<<" "; 77 cishu+=1; 78 } 79 int main() 80 { 81 Fraction f1,f2,f3; 82 while(cin>>f1>>f2) 83 { 84 if(f1==0&&f2==0) 85 break; 86 f3=f1-f2; 87 f3.output(); 88 f3=f1/f2; 89 f3.output(); 90 cout<<endl; 91 } 92 return 0; 93 }