一本通-1209:分数求和¶
【题目描述】 输入n个分数并对他们求和,并用最简形式表示。所谓最简形式是指:分子分母的最大公约数为1/1;若最终结果的分母为1,则直接用整数表示。
如:⅚、10/3均是最简形式,而3/6需要化简为½,3/1需要化简为3。
分子和分母均不为0,也不为负数。
【输入】 第一行是一个整数n,表示分数个数,1≤n≤10;
接下来n行,每行一个分数,用"p/q"的形式表示,不含空格,p,q均不超过10。
【输出】 输出只有一行,即最终结果的最简形式。若为分数,用"p/q"的形式表示。
【输入样例】 2 ½ ⅓
【输出样例】 ⅚
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <string>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <set>
#include <algorithm>
using namespace std;
class num
{
friend ostream & operator<<(ostream & os, const num & obj);
private:
int a, b;
public:
num(string & s)
{
int n = s.size();
int pos = -1;
for (int i = 0; i < n; ++i) {
if (s[i] == '/') {
pos = i; break;
}
}
a = toNum(s.substr(0, pos));
b = toNum(s.substr(pos + 1));
}
inline int toNum(const string & s)
{
int res = 0;
for (size_t i = 0; i < s.size(); ++i) {
res = res * 10 + s[i] - '0';
}
return res;
}
int GCD(int x, int y)
{
return y == 0 ? x : GCD(y, x % y);
}
num & operator+=(const num & obj)
{
int tmpA = a * obj.b + b * obj.a;
int tmpB = b * obj.b;
int d = GCD(tmpA, tmpB);
a = tmpA / d;
b = tmpB / d;
return *this;
}
};
ostream & operator<<(ostream & os, const num & obj)
{
os << obj.a << "/" << obj.b << endl;
return os;
}
int main()
{
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n; cin >> n;
string s; cin >> s;
num obj(s);
for (int i = 1; i < n; ++i) {
cin >> s;
num frac(s);
obj += frac;
}
cout << obj;
return 0;
}