这两天比赛遇到了一个分数的题,回想起来上课写的分数类,当时写的用上去以后漏洞百出,于是用闲暇时间又重写了一个作为模板。
#include<iostream> #include<algorithm> #include<cmath> using namespace std; int gcd(int x, int y) //最大公因数(能整除x y 两数的最大整数) { x = abs(x); y = abs(y); return y == 0 ? x : gcd(y, x%y); } int lcm(int a, int b) //最小公倍数(能将a b 整除的最小整数) { a = abs(a); b = abs(b); int m; a>b?1:m=a,a=b,b=m; return a*b / gcd(a, b); } class Fractions { public: int numerator;//分子 缩写 nmrtr int denominator;//分母 缩写 dnmtr Fractions(int nmrtr = 0,int dnmtr = 1):numerator(nmrtr),denominator(dnmtr) //无参则为0 { denominator = denominator == 0 ? denominator = 1 : denominator;//分母不为0,弱输入0,自动转换为1 变为整数 } Fractions friend operator + (Fractions a,Fractions b) { Fractions c; if (a.numerator == 0) c = b; else { int deno_lcm = lcm(a.denominator,b.denominator); int nmrtr = a.numerator * (deno_lcm/a.denominator) + b.numerator * (deno_lcm / b.denominator); int dnmtr = deno_lcm; int c_gcd = gcd(nmrtr,dnmtr); c.numerator = nmrtr / c_gcd; c.denominator = dnmtr / c_gcd; } return c; } Fractions friend operator + (Fractions a, int b) { Fractions c; if (a.numerator == 0) { c.numerator = b; c.denominator = 1; } else { int nmrtr = a.numerator + b * a.denominator; int dnmtr = a.denominator; int c_gcd = gcd(nmrtr, dnmtr); c.numerator = nmrtr / c_gcd; c.denominator = dnmtr / c_gcd; } return c; } Fractions friend operator - (Fractions a, Fractions b) { Fractions c; if (a.numerator == 0) { c = b; c.numerator = 0-c.numerator; } else { int deno_lcm = lcm(a.denominator, b.denominator); int nmrtr = a.numerator * (deno_lcm / a.denominator) - b.numerator * (deno_lcm / b.denominator); int dnmtr = deno_lcm; int c_gcd = gcd(nmrtr, dnmtr); c.numerator = nmrtr / c_gcd; c.denominator = dnmtr / c_gcd; } return c; } Fractions friend operator - (Fractions a, int b) { Fractions c; if (a.numerator == 0) { c.numerator = 0-b; c.denominator = 1; } else { int nmrtr = a.numerator - b * a.denominator; int dnmtr = a.denominator; int c_gcd = gcd(nmrtr, dnmtr); c.numerator = nmrtr / c_gcd; c.denominator = dnmtr / c_gcd; } return c; } istream friend &operator >> (istream &input, Fractions &a) { input >> a.numerator; input.get(); input >> a.denominator; return input; } ostream friend &operator << (ostream &output,Fractions &a) { if (a.numerator == 0) output << 0; else if (a.denominator == 1) output << a.numerator; else output << a.numerator << "/" << a.denominator; return output; } }; int main() { Fractions a; Fractions b; Fractions x; char c; while (cin >> a >> c >> b) { if (c == '+') { x=a+b; cout<< x << endl; } else { x=a-b; cout << x << endl; } } return 0; }
881 total views, no views today