题目大意:给出N个有理数 num / den,计算它们的和并以最简带分数形式输出。
有理数运算,主要有以下几个注意点:
① 最大公约数的求法,辗转相除法。
② 化简过程中,让分母为正数,这样在输出时可以直接输出分子,包含了符号。然后分子分母约去绝对值的最大公约数。
③ 输出过程中注意分母为1的情况。
AC代码:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
struct rationalNum
{
int num;
int den;
friend ostream& operator<<(ostream &os, const rationalNum &a)
{
if(a.den == 1) os << a.num;
else
{
if(abs(a.num) > a.den) os << a.num / a.den << " " << abs(a.num) % a.den << "/" << a.den;
else os << a.num << "/" << a.den;
}
return os;
}
};
int gcd(int a, int b)
{
if(b == 0) return a;
gcd(b, a % b);
}
void reduction(rationalNum &a)
{
if(a.den < 0)
{
a.den *= -1;
a.num *= -1;
}
int g = gcd(abs(a.num), a.den);
a.num /= g;
a.den /= g;
}
rationalNum add(rationalNum &a, rationalNum &b)
{
rationalNum sum = {a.num * b.den + a.den * b.num, a.den * b.den};
reduction(sum);
return sum;
}
int main()
{
int N;
scanf("%d", &N);
rationalNum sum = {0, 1};
for (int i = 0; i < N; ++i)
{
int num, den;
scanf("%d/%d", &num, &den);
rationalNum a = {num, den};
sum = add(sum, a);
}
cout << sum;
return 0;
}