1081 Rational Sum (20分)

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 ... 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.

Output Specification:

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.

Sample Input 1:

5
2/5 4/15 1/30 -2/60 8/3

Sample Output 1:

3 1/3

Sample Input 2:

2
4/3 2/3

Sample Output 2:

2

Sample Input 3:

3
1/3 -1/6 1/8

Sample Output 3:

7/24

题目描述:分数求和。


输入:第一行n表示分数的个数,第二行n个分数。

输出:分数之和。输出格式 1)4/3输出1 2/3;2)4 /4 输出 1;3)2/3输出2/3


解题思路:我习惯将程序分块写,这样程序看起来比较直观清晰;将所有分数加起来,可以先记录第一个分数,分子为a1、分母为b1,接着读第二个分数,第二个分数分子为a2,分母为b2,接着就可以将两个分数进行计算了,然后将计算结果分别再存入a1和b1;后面读入的分数都存在a2和b2中,重复上述过程。得到的结果a1和b1按照题目规定输出格式输出。

两个分数相加的过程:例如2/5和4/15相加,想求出两个分母的最大公因数为5,两个分母同时除于5,分别得到b1=1,b2=3,将分子a1乘与b2,a2乘与b1,则a1=6,a2=4,此时,分数分别为6/1和4/3,让a1=a1+a2=10,b1 = b1*b2*gcd(b1,b2)=15(分母进行通分的过程),这样就能将两分数相加的结果放入a1和b1了,即2/5 + 4 / 15 = 10 / 15。


#include<bits/stdc++.h>
using namespace std;
int n, a1, b1, a2, b2;
int gcd(int a, int b){ return a == 0 ? b : gcd(b % a, a); } 
void sum(){
	int g = gcd(b1,b2);
	b1 /= g;
	b2 /= g;
	a1*=b2; a2 *= b1;
	a1 += a2;
	b1 *= b2*g;
}
int main()
{
	scanf("%d", &n);
	for(int i=0; i<n; i++){
		if(i==0) scanf("%d/%d", &a1, &b1);
		else{
			scanf("%d/%d", &a2, &b2);
			sum();
		}
	}
	int g = gcd(a1,b1);
	a1 /= g; b1 /= g;
	if(a1%b1==0) printf("%d\n", a1/b1);
	else if(a1>b1) printf("%d %d/%d\n", a1/b1, a1%b1, b1);
	else printf("%d/%d", a1%b1, b1);
	return 0;
}