有理数类运算

#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;
}
上一篇:P3809 【模板】后缀排序 良心讲解


下一篇:ZOJ 3876 JAVA