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

题目大意

给定分子/分母形式的若干个有理数,计算它们的和并以题目要求的形式输出。

解题思路

  1. 建立结构体储存分数;
  2. 在计算时存储第一个分数的绝对值,并记录第一个分数的符号;
  3. 将后序每个数字与暂时的结果进行计算,直到输入结束;
  4. 按照题目要求输出结果,并返回零值(需要注意特判结果为零的输出)。

代码

#include<stdio.h>
long long gcd(long long a,long long b){
    if(b==0){
        return a;
    }else{
        return gcd(b,a%b);
    }
}//最大公约数

struct Num{
    long long numerator,denominator;
}num,ans;

int main(){
    int i,N,flaga,flagn;
    long long pub,a,n,integer;
    scanf("%d",&N);
    scanf("%lld/%lld",&ans.numerator,&ans.denominator);
    if(ans.numerator>=0){
        flaga=1;
    }else{
        flaga=-1;
        ans.numerator=-ans.numerator;
    }
    for(i=1;i<N;i++){
        scanf("%lld/%lld",&num.numerator,&num.denominator);
        if(num.numerator>=0){
            flagn=1;
        }else{
            flagn=-1;
            num.numerator=-num.numerator;
        }
        pub=gcd(ans.denominator,num.denominator);
        a=ans.denominator/pub;
        n=num.denominator/pub;
        ans.denominator=a*n*pub;
        ans.numerator=flaga*ans.numerator*n+flagn*num.numerator*a;
        if(ans.numerator>=0){
            flaga=1;
        }else{
            flaga=-1;
            ans.numerator=-ans.numerator;
        }
        pub=gcd(ans.numerator,ans.denominator);
        ans.denominator/=pub;
        ans.numerator/=pub;
    }
    if(flaga==-1){
        printf("-");
    }
    integer=ans.numerator/ans.denominator;
    ans.numerator%=ans.denominator;
    if(integer){
        printf("%d",integer);
        if(ans.numerator){
            printf(" ");
        }else{
            printf("\n");
        }
    }
    if(ans.numerator){
        printf("%d/%d\n",ans.numerator,ans.denominator);
    }
    if(integer==0&&ans.numerator==0){
        printf("0\n");
    }
    return 0;
}

运行结果

PAT-A1081 Rational Sum 题目内容及题解

 

相关文章: