具体题意:
原题链接:This
输入 2 个分数并对他们求和,并用最简形式表示。所谓最简形式是指:分子分母的最大公约数为 1;若最终结果的分母为 1,则直接用整数表示。
如:5/6、10/3均是最简形式,而3/6 要化简为1/2 ,6/2 化简为3。
Input
1/6
1/3
Output
1/2
解题思路:
这道题我们要想到一个分数相加通用的公式:
解题思路到此结束。
在输出时的一个重点:
可以像我一样重载输出,也可以用纯变量的方式。
但是,都注意了!(敲黑板)
当分子分母直接成倍数关系时,输出 整数值即可。
重载方式代码:
ostream& operator << (ostream &out, const Double &x) {
if (x.p % x.q != 0) cout << x.p << '/' << x.q;
else cout << x.p / x.q;
return out;
}
My Code:
Class类做法,大佬勿喷。
#include <bits/stdc++.h>
#include <numeric>
#define int long long
using namespace std;
int lcm(int a, int b) {
return a * b / __gcd(a, b);
}
class Double{
public:
int p, q;
Double() {
p = q = -1;
}
Double operator + (const Double &x) const {
Double Ans;
Ans.p = p * x.q + q * x.p;
Ans.q = q * x.q;
Ans.YueFen();
return Ans;
}
void YueFen() {
int Gc = __gcd(p, q);
p /= Gc;
q /= Gc;
return;
}
};
istream& operator >> (istream &in, Double &x) {
char tmp;
cin >> x.p >> tmp >> x.q;
return in;
}
ostream& operator << (ostream &out, const Double &x) {
if (x.p % x.q != 0) cout << x.p << '/' << x.q;
else cout << x.p / x.q;
return out;
}
Double a, b;
signed main() {
cin >> a >> b;
cout << a + b;
return 0;
}