Fraction重载

这是一个有关分数的加减乘除,输入以及输出的c++简单重载~~
#include
#include
using namespace std;

int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}

class Fraction
{
private:
int fz,fm;
public:
Fraction(int z=1,int m=1);
Fraction(Fraction &c);
Fraction operator +(const Fraction &a);
Fraction operator -(const Fraction &a);
Fraction operator *(const Fraction &a);
Fraction operator /(const Fraction &a);
friend istream & operator >>(istream &in,Fraction &a);
friend ostream & operator <<(ostream &out,Fraction &a);
int gcd(int a,int b);
};

Fraction::Fraction(Fraction &c)
{
fz=c.fz;fm=c.fm;
int a,b;
a=fz;b=fm;
fz=fz/gcd(a,b);
fm=fm/gcd(a,b);
if(fm<0)
{fz=-fz;fm=-fm;}
}

int Fraction::gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}

Fraction::Fraction(int z,int m)
{
fz=z;
fm=m;
int a,b;
a=fz;b=fm;
fz=fz/gcd(a,b);
fm=fm/gcd(a,b);
if(fm<0)
{fz=-fz;fm=-fm;}
}

Fraction Fraction:: operator +(const Fraction &a)
{
Fraction b;
b.fz=fza.fm+fma.fz;
b.fm=fma.fm;
int a1,b1;
a1=b.fz;b1=b.fm;
b.fz=b.fz/gcd(a1,b1);
b.fm=b.fm/gcd(a1,b1);
if(b.fm<0)
{b.fz=-b.fz;b.fm=-b.fm;}
return b;
}
Fraction Fraction:: operator -(const Fraction &a)
{
Fraction b;
b.fz=fz
a.fm-fma.fz;
b.fm=fm
a.fm;
int a1,b1;
a1=b.fz;b1=b.fm;
b.fz=b.fz/gcd(a1,b1);
b.fm=b.fm/gcd(a1,b1);
if(b.fm<0)
{b.fz=-b.fz;b.fm=-b.fm;}
return b;
}
Fraction Fraction:: operator (const Fraction &a)
{
Fraction b;
b.fz=fz
a.fz;
b.fm=fma.fm;
int a1,b1;
a1=b.fz;b1=b.fm;
b.fz=b.fz/gcd(a1,b1);
b.fm=b.fm/gcd(a1,b1);
if(b.fm<0)
{b.fz=-b.fz;b.fm=-b.fm;}
return b;
}
Fraction Fraction:: operator /(const Fraction &a)
{
Fraction b;
b.fz=fz
a.fm;
b.fm=fm*a.fz;
int a1,b1;
a1=b.fz;b1=b.fm;
b.fz=b.fz/gcd(a1,b1);
b.fm=b.fm/gcd(a1,b1);
if(b.fm<0)
{b.fz=-b.fz;b.fm=-b.fm;}
return b;
}

istream & operator >>(istream &in,Fraction &a)
{
cin>>a.fz>>a.fm;
int a1,b1;
a1=a.fz;b1=a.fm;
a.fz=a.fz/gcd(a1,b1);
a.fm=a.fm/gcd(a1,b1);
if(a.fm<0)
{a.fz=-a.fz;a.fm=-a.fm;}
return in;
}
ostream & operator <<(ostream &out,Fraction &a)
{
cout<<a.fz<<"/"<<a.fm;
return out;
}

有两点要注意的地方:

1,为了方便,gcd是公有函数,在其他的重载中,每次我们都将调用一次gcd来完成分数约分。

2.在每个运算重载的末尾我们都要进行一次
if(fm<0)
{fz=-fz;fm=-fm;}
}
为什么要这一步呢,这是因为gcd会改变分数正负。
如gcd(-2,48) 答案是-2
所以再用分子,分母去除的话我们就不能保证分母恒为正了,所以每个gcd后都要加一个。
emmm,码完后才发现这一大串完全可以写成一个函数,看着怪难受。。。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值