题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805386161274880

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个分数,求分数的和,并化为分数的形式输出。

#include<iostream>
using namespace std;
typedef long long ll;
ll gcd(int x,int y){
	if(!y){
		return x;
	}else{
		return gcd(y,x%y);
	}
}
int main(){
	ll n,a,b;
	ll sum_a=0,sum_b=1;
	ll val;
	scanf("%lld",&n);
	for(int i=0;i<n;i++){
		scanf("%lld/%lld",&a,&b);
		val=gcd(a,b);
		a=a/val;
		b=b/val;
		sum_a=a*sum_b+b*sum_a;
		sum_b=b*sum_b;
		val=gcd(sum_a,sum_b);
		sum_a=sum_a/val;
		sum_b=sum_b/val;

	}
	if(sum_a==0){
		printf("0\n");
	}else{
		ll ans=sum_a/sum_b;
		sum_a=sum_a-(sum_b*ans);
		if(ans!=0){
			if(sum_a!=0){
				printf("%lld %lld/%lld",ans,sum_a,sum_b);
			}else{
				printf("%lld",ans);
			}
		}else{
			printf("%lld/%lld",sum_a,sum_b);
		}
	}
	return 0;
}

PAT (Advanced Level) Practice — 1081 Rational Sum (20 分)

相关文章:

  • 2021-08-09
  • 2021-05-17
  • 2021-10-05
  • 2021-05-15
  • 2021-08-01
  • 2021-06-27
  • 2021-12-02
猜你喜欢
  • 2021-05-16
  • 2021-10-02
  • 2021-12-07
  • 2021-10-09
  • 2021-05-22
  • 2022-01-17
  • 2021-04-08
相关资源
相似解决方案