從今天開始刷題 =俩滥。=
會(huì)經(jīng)常更新的
題目描述
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>
using namespace std;
// 輾轉(zhuǎn)相除
long long gcd(long long a, long long b)
{
if(0 == b) return a;
else return gcd(b, a%b);
}
int main()
{
// freopen("input.txt", "r", stdin);
int num = 0;
cin >> num;
long int numerators[100];
long int denominator[100];
// 通分并相加
long long product = 1, sum = 0;
for (int i=0; i<num; i++)
{
char ctemp = 0;
cin >> numerators[i] >> ctemp >> denominator[i];
product *= denominator[i];
}
for (int i=0; i<num; i++)
{
sum += (numerators[i] * product / denominator[i]);
}
// 約分
auto temp = abs(gcd(sum, product));
sum /= temp;
product /= temp;
if (0 == sum%product) // 整除
{
cout << sum/product << endl;
}
else if (abs(sum)>product) // 帶分?jǐn)?shù)
{
cout << sum/product << " " << sum%product << "/" << product << endl;
}
else cout << sum << "/" << product << endl; // 真分?jǐn)?shù)
return 0;
}
Tips:
1.gcd求出的最大公約數(shù)可能為負(fù)值,需要判斷