有理数类运算

#include<iostream>
using namespace std;
class Num{
public:
    Num(int a,int b);//构造函数,因为不需要申请新的节点,所以用不着复制赋值,移动复制,移动构造
    ~Num();//析构函数
    Num operator+(Num &other);//加
    Num operator-(Num &other);//减
    Num operator*(Num &other);//乘
    Num operator/(Num &other);//除
    friend ostream& operator << (ostream& out,const Num& other);
    void jianhua();
private:
    int x,y;
};
Num::Num(int a,int b)
{
    x=a;
    y=b;
}
Num Num::operator+(Num &other)
{
    Num result(0,0);
    result.x=x*other.y+other.x*y;
    result.y=y*other.y;
    return result;
}
Num Num::operator-(Num &other)
{
    Num result(0,0);
    result.x=x*other.y-other.x*y;
    result.y=y*other.y;
    return result;
}
Num Num::operator*(Num &other)
{
    Num result(0,0);
    result.x=x*other.x;
    result.y=y*other.y;
    return result;
}
Num Num::operator/(Num & other)
{
    Num result(0,0);
    result.x=x*other.y;
    result.y=other.x*y;
    return result;
}
void Num:: jianhua()
{
 for(int i=2;i<=100;i++){
  if((x%i==0)&&(y%i==0)){
   x=x/i;
   y=y/i;
   i=2;
  }
 }
 if((x<0&&y<0)||(x>0&&y<0))
 {
     x=-x;
     y=-y;
 }
}
ostream& operator << (ostream& out,const Num& other)
{
 if(other.y==1)
    {
        out<<other.x<<"\t";
    }
    else
        out<<other.x<<"/"<<other.y<<"\t";
} 
Num::~Num()
{
}
int main()
{
    int a,b,c,d;
    cin>>a>>b>>c>>d;
    Num fir(a,b);
    Num sec(c,d);
    fir.jianhua();
    sec.jianhua();
    cout<<fir<<endl;
    cout<<sec<<endl;
    Num add=fir+sec;
    Num jian=fir-sec;
    Num cheng=fir*sec;
    Num chu=fir/sec;
    add.jianhua();
    jian.jianhua();
    cheng.jianhua();
    chu.jianhua();
 cout<<add<<jian<<cheng<<chu;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值