加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
有理数计算.cpp 2.99 KB
一键复制 编辑 原始数据 按行查看 历史
墨澜1024 提交于 2022-06-05 09:55 . 有理数计算
#include<iostream>
using namespace std;
class Rational
{
public:
Rational(long a, long b)
{
negetive = false;
isZero = false;
if (b == 0)
{
isZero = true;
return;
}
if (a < 0)
{
negetive = !negetive;
}
if (b < 0)
{
negetive = !negetive;
}
integer = a / b;
numerator = a - integer * b;
denominator = abs(b);
if (numerator < -1 || numerator > 1)
{
int gcd = CalcGCD(abs(numerator), denominator);
if (gcd)
{
numerator /= gcd;
denominator /= gcd;
}
}
totalnumber = integer * denominator + numerator;
}
Rational operator+(const Rational& r)const
{
long a = totalnumber * r.denominator + r.totalnumber * denominator;
long b = denominator * r.denominator;
return Rational(a, b);
}
Rational operator-(const Rational& r)const
{
long a = totalnumber * r.denominator - r.totalnumber * denominator;
long b = denominator * r.denominator;
return Rational(a, b);
}
Rational operator*(const Rational& r)const
{
long a = totalnumber * r.totalnumber;
long b = denominator * r.denominator;
return Rational(a, b);
}
Rational operator/(const Rational& r)const
{
long a = totalnumber * r.denominator;
long b = denominator * r.totalnumber;
return Rational(a, b);
}
private:
long CalcGCD(long numerator, long denominator)
{
if (denominator == 0)
return numerator;
return CalcGCD(denominator, numerator % denominator);
}
friend ostream& operator<<(ostream& _cout, const Rational& r)
{
if (r.isZero)
{
_cout << "Inf";
return _cout;
}
if (r.integer == 0 && r.numerator == 0)
{
_cout << "0";
return _cout;
}
if (r.negetive)
{
_cout << "(-";
}
if (r.integer)
{
_cout << abs(r.integer);
if (r.numerator)
{
_cout << " ";
}
}
if (r.numerator)
{
_cout << abs(r.numerator) << "/" << r.denominator;
}
if (r.negetive)
{
_cout << ")";
}
return _cout;
}
private:
long numerator, denominator, integer, totalnumber;
bool negetive;
bool isZero;
};
int main()
{
long int a1, b1, a2, b2;
while (scanf("%lld/%lld %lld/%lld", &a1, &b1, &a2, &b2) != EOF)
{
Rational r1(a1, b1);
Rational r2(a2, b2);
cout << r1 << " + " << r2 << " = " << r1 + r2 << endl;
cout << r1 << " - " << r2 << " = " << r1 - r2 << endl;
cout << r1 << " * " << r2 << " = " << r1 * r2 << endl;
cout << r1 << " / " << r2 << " = " << r1 / r2 << endl;
}
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化