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
/* All rights reserved. * 文件名称:test.cpp * 作者:陈丹妮 * 完成日期:2015年 7 月 2 日 * 版 本 号:v1.0 */ #include <iostream> using namespace std; class Fraction { private: int x; int y; int e; public: Fraction(int a=0,int b=1):x(a),y(b) { e=0; } friend istream& operator>>(istream& input,Fraction &f); bool operator ==(int a); void output(); Fraction operator -(Fraction &f1); Fraction operator /(Fraction &f1); }; istream& operator>>(istream& input,Fraction &f) { input>>f.x>>f.y; return input; } bool Fraction::operator==(int a) { if(x==a) return true; else return false; } Fraction Fraction::operator -(Fraction &f1) { Fraction f; f.x=x*f1.y-f1.x*y; f.y=y*f1.y; return f; } Fraction Fraction::operator /(Fraction &f1) { Fraction f; f.x=x*f1.y; f.y=y*f1.x; return f; } void Fraction::output() { int r,m=x,n=y,t; if(m<n) { t=n; n=m; n=t; } while(n!=0) { r=m%n; m=n; n=r; } if(y==m) cout<<x/m; else if(x/m<0&&y/m<0) cout<<(-1)*x/m<<'/'<<(-1)*y/m; else if(y/m<0) cout<<-x/m<<'/'<<-y/m; else cout<<x/m<<'/'<<y/m; if(e==0) cout<<" "; e++; } 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; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-12-07 09:55:06