PAT(Advanced) 1081 Rational Sum(20 分)
阿新 • • 發佈:2018-11-07
Given N rational numbers in the form numerator/denominator
, you are supposed to calculate their sum.
Input Specification:
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 ...
Output Specification:
For each test case, output the sum in the simplest form integer numerator/denominator
where integer
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.
解答:對於該題,我們可以用結構體來儲存一個分數的上下標,然後分數相加,相加後需要化簡,最後根據題目要求輸出結果。
這道題真的是C語言模組化程式設計的優勢體現啊,很棒的題目。
AC程式碼如下:
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
typedef struct{
int up, down;
}fraction;
int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
fraction reduction(fraction re)
{
if(re.up != 0)
{
int tmp = gcd(abs(re.up), abs(re.down));
re.up /= tmp;
re.down /= tmp;
}
else
{
re.down = 1;
}
return re;
}
fraction add(fraction t, fraction sum)
{
fraction tmp;
tmp.up = t.up * sum.down + t.down * sum.up;
tmp.down = sum.down * t.down;
tmp = reduction(tmp);
return tmp;
}
int main()
{
int n;
fraction sum;
sum.up = 0; sum.down = 1;
scanf("%d", &n);
for(int i = 0; i < n; ++i)
{
fraction t;
scanf("%d/%d", &t.up, &t.down);
sum = add(t, sum);
}
int integer = sum.up / sum.down;
sum.up %= sum.down;
if(integer == 0)
{
if(sum.up != 0)
printf("%d/%d\n", sum.up, sum.down);
else
printf("0\n");
}
else
{
if(sum.up != 0)
printf("%d %d/%d\n", integer, sum.up, sum.down);
else
printf("%d\n", integer);
}
return 0;
}