题目描述
Given N rational numbers in the form “numerator/denominator”, you are supposed to calculate their sum.
输入描述:
Each input file contains one test case. Each case starts with a positive integer N (<=100), followed in the next line N rational numbers “a1/b1 a2/b2 …” where all the numerators and denominators are in the range of “long int”. If there is a negative number, then the sign must appear in front of the numerator.
输出描述:
For each test case, output the sum in the simplest form “integer numerator/denominator” where “integer” is the integer part of the sum, “numerator” < “denominator”, and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0.
输入例子:
5
2/5 4/15 1/30 -2/60 8/3
输出例子:
3 1/3
# include<iostream>
#include <stdio.h>
#include<algorithm>
using namespace std;
struct fraction {
int up, down;
fraction() { up = 0, down = 1; }
};
int gcd(int a, int b)
{
a = abs(a), b = abs(b);
if (a < b)swap(a, b);
return b == 0 ? a : gcd(b, a%b);
}
fraction reduction(fraction x)
{
if (x.down < 0)x.up = -x.up, x.down = -x.down; //如果分母为负数则负号转移到分子上
if (x.down == 0)x.up = 1;
else
{
int d = gcd(x.up, x.down);
x.up /= d;
x.down /= d;
}
return x;
}
fraction add(fraction x, fraction y)
{
fraction result;
result.up = x.up*y.down + y.up*x.down;
result.down = x.down*y.down;
result = reduction(result);
return result;
}
void showresult(fraction x)
{
if (x.down == 1) printf("%d", x.up);
else if (abs(x.up) < x.down) printf("%d/%d", x.up, x.down);
else printf("%d %d/%d", x.up / x.down, abs(x.up) % x.down, x.down);
}
int main()
{
int n;
scanf("%d", &n);
fraction result;
while (n--)
{
fraction temp;
scanf("%d/%d", &temp.up, &temp.down);
result = add(result, temp);
}
showresult(result);
return 0;
}