📄 ration.cpp
字号:
#include<iostream>
#include"rational.h"
using namespace std;
//化简
void rational::simplify(rational &r)
{
int x,y;
x=r.get_fenzi();
y=r.get_fenmu();
int tem;
if(x<y)
{
tem=x;x=y;y=tem;
}
while(x%y)
{
tem=x%y;
x=y;
y=tem;
}
r.set_fenzi()(r.get_fenzi()/y);
r.set_fenmu()(r.get_fenmu()/y);
}
inline int rational operator +(rational &r1,rational &r2) //重载+
{
rational temp;
temp.set_fenzi(r1.get_fenzi() * r2.get_fenmu()+r1.get_fenmu() * r2.get_fenzi());
temp.set_fenmu(r1.get_fenmu() * r2.get_fenmu());
return temp;
}
inline int rational operator -(rational &r1,rational &r2) //重载-
{
rational temp;
temp.set_fenzi(r1.get_fenzi() * r2.get_fenmu()-r1.get_fenmu() * r2.get_fenzi());
temp.set_fenmu(r1.get_fenmu() * r2.get_fenmu());
return temp;
}
inline int rational operator *(rational &r1,rational &r2) //重载*
{
rational temp;
temp.set_fenzi(r1.get_fenzi() * r2.get_fenzi());
temp.set_fenmu(r1.get_fenmu() * r2.get_fenmu());
return temp;
}
inline int rational operator /(rational &r1,rational &r2) //重载/
{
rational temp;
temp.set_fenzi(r1.get_fenzi() * r2.get_fenmu());
temp.set_fenmu(r1.get_fenmu() * r2.get_fenzi());
return temp;
}
//比较大小
int sign(int value)
{
if(value>0) return 1;
else if(value==0) return 0;
else return -1;
}
int rational::compare(const rational &r) const
{
return (r1.get_fenzi()*r2.get_fenmu()-r1.get_fenmu()*r2.get_fenzi())*sign(r1.get_fenmu())*sign(r2.get_fenmu);
}
inline bool operator ==(const rational &r1,const rational &r2)//重载==运算符
{
return compare(r1,r2)==0;
}
inline bool operator >(const rational &r1,const rational &r2)//重载>运算符
{
return compare(r1,r2)>0;
}
inline bool operator <(const rational &r1,const rational &r2)//重载<运算符
{
return compare(r1,r2)<0;
}
//输入
inline void rational::istream &operator >>(istream &in,rational &r)
{
int a,b;
in>>a;
char c;
in>>c;
if(c=='/')
in>>b;
else
{
in.putback(c);
b=1;
}
rational R(a,b);
r=R;
return in;
}
//输出
inline void rational::ostream &operator <<(ostream &out,const rational &r)
{
out<<r.get_fenzi()<<'/'<<r.get_fenmu();
return out;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -