PAT Advanced 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. 输入分子、分母,化简
  2. 计算累加分数和与下一个分数和,化简
  3. 累加完成后,假分数转换为真分数,打印整数部分和分式部分

易错点

  1. 若和为0,要输出“0”(否则测试点4错误)

知识点

  1. long long类型的数据输入/输出
    输入:scanf("%lld",&n);
    输出:printf("%lld",n);

Code

Code 01

#include <iostream>
using namespace std;
// 求公约数
int gcd(long long a, long long b) {
	return b==0?abs(a):gcd(b, a%b);
}
// 化简分式
void reduction(long long &a, long long &b) {
	int gcdvalue = gcd(a,b);
	a /= gcdvalue;
	b /= gcdvalue;
}
int main(int argc,char * argv[]) {
	long long n,a,b,suma=0,sumb=1,gcdvalue;
	scanf("%lld",&n);
	for(int i=0; i<n; i++) {
		scanf("%lld/%lld",&a,&b);
		reduction(a,b);
		suma=a*sumb+suma*b;
		sumb=b*sumb;
		reduction(suma,sumb);
	}
	long long itg = suma/sumb;
	suma = suma-(sumb*itg);
	if(itg!=0) {
		printf("%lld",itg);
		if(suma!=0)printf(" ");
	}
	if(suma!=0)printf("%lld/%lld",suma,sumb);
	if(itg==0&&suma==0)printf("0");
	return 0;
}
原文地址:https://www.cnblogs.com/houzm/p/12261856.html