Rational Sum(PAT)

    技术2025-04-08  9

    1.题目描述

    Given N rational numbers in the form “numerator/denominator”, you are supposed to calculate their sum. 给定N个有理数的形式“分子/分母”,你应该计算他们的和。

    2.输入描述:

    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. 每个输入文件包含一个测试用例。每种情况都以正整数N(<=100)开头,在下一行N有理数“A1/b1a2/b2.”所有分子和分母都在“long int”的范围内。如果有负数,则符号必须出现在分子前面。

    3.输出描述:

    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. 对于每个测试用例,输出最简单形式的和“整数分子/分母”,其中“整数”是和的整数部分,“分子”<“分母”,分子和分母没有公共因子。如果整数部分为0,则只能输出小数部分。

    4.输入例子:

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

    5.输出例子:

    3 1/3

    6.源代码:

    #include<stdio.h> int gcd(int x,int y)//求最大公约数 { return x?gcd(y%x,x):y; } int main() { int A,B,N; scanf("%d",&N); int sum_A=0,sum_B=1;//初始化分数之和的分子和分母(分母不能为零) for(int i=0;i<N;i++) { scanf("%d/%d",&A,&B); sum_A=sum_A*B+sum_B*A;//分子之和 sum_B=sum_B*B;//分母之和 } int sum=sum_A/sum_B;//求整 sum_A%=sum_B;//约分 int T=gcd(sum_A,sum_B); if(T<0) //使最大公约数为正数 T=-T; if(sum_A&&sum) printf("%d %d/%d",sum,sum_A/T,sum_B/T); else if(!sum_A) printf("%d",sum); else printf("%d/%d",sum_A/T,sum_B/T); return 0; }
    Processed: 0.011, SQL: 9