代码拉取完成,页面将自动刷新
#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;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。