编写分数类Fraction,实现两个分数的加、减、乘和除四则运算。主函数已给定。
标签:c++ class iostream 类 namespace
1 2 -1 2
4 3 3 4
0 0 0 0
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; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
第十七周oj刷题——Problem B: 分数类的四则运算【C++】
标签:c++ class iostream 类 namespace
原文地址:http://blog.csdn.net/nufangdongde/article/details/46725161