您的位置:首页 > 其它

练手_分数加减乘除

2008-09-01 14:51 197 查看
#include <iostream>

using namespace std;

/*

*学会了怎么重载>>和<<

*功能还不是很全面,只支持最简单的-_-另外输入输出也没判断错..而且只能输入正的...why?见下:

*纯属练手

*/

bool sng;

struct fac

{

int h,r;

inline int gcd(int a,int b){return b?gcd(b,a%b):a;}

inline void make(){int tmp=gcd(h,r);h/=tmp,r/=tmp;}

friend inline istream& operator>>(istream& in,fac& f)

{

char c;

f.r=0;

while(f.r==0) {in>>f.h>>c>>f.r;if(f.r==0)cout<<"Invalid input!/n";}

return in;

}

friend inline ostream& operator<<(ostream& out,const fac& f)

{

if(sng)out<<'-';

if(f.r==1)

out<<f.h;

else

if(f.r==f.h)

out<<1;

else

if(f.h==0)

out<<0;

else

out<<f.h<<'/'<<f.r;

return out;

}

inline fac operator+(const fac& b)

{

fac tmp;

tmp.r=r*b.r/gcd(r,b.r);

tmp.h=tmp.r/r*h+tmp.r/b.r*b.h;

tmp.make();

return tmp;

}

inline fac operator-(const fac& b)

{

fac tmp;bool sign=false;

tmp.r=r*b.r/gcd(r,b.r);

tmp.h=tmp.r/r*h-tmp.r/b.r*b.h;

if(tmp.h<0)sng=true,tmp.h*=-1;

tmp.make();

return tmp;

}

inline fac operator*(const fac& b)

{

fac tmp;

tmp.r=r*b.r;

tmp.h=h*b.h;

if(tmp.r*tmp.h<0)sng=true,tmp.r=abs(tmp.r),tmp.h=abs(tmp.h);

tmp.make();

return tmp;

}

inline fac operator/(const fac& b)

{

fac tmp;

tmp.r=r*b.h;

tmp.h=h*b.r;

if(tmp.r*tmp.h<0)sng=true,tmp.r=abs(tmp.r),tmp.h=abs(tmp.h);

tmp.make();

return tmp;

}

};

int main()

{

fac a,b;

while(cin>>a>>b)

{

sng=false;

cout<<a+b<<endl;

cout<<a-b<<endl;

sng=false;

cout<<a*b<<endl;

sng=false;

cout<<a/b<<endl;

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐