PAT (Advanced Level) Practice A1081 Rational Sum (20 分)(C++)(甲级)(分数相加)

版权声明:假装有个原创声明……虽然少许博文不属于完全原创,但也是自己辛辛苦苦总结的,转载请注明出处,感谢! https://blog.csdn.net/m0_37454852/article/details/86592707

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

using namespace std;
#include<algorithm>
#include<iostream>
#include<cstdio>

typedef struct Fraction//分数结构体
{
    long long int up, down;//分子分母
}Fraction;
Fraction result, A, B;

long long int gcd(long long int a, long long int b)//求最大公约数
{
    if(!b) return a;
    return gcd(b, a%b);
}

Fraction reduction(Fraction A)//化简
{
    if(A.down < 0) A.up = -A.up, A.down = -A.down;//分母为负则取相反数
    if(!A.up) A.down = 1;
    else
    {
        long long int d = gcd(A.up, A.down);//求最大公约数
        A.up /= d, A.down /= d;
    }
    return A;
}

int main()
{
    int N;
    scanf("%d", &N);
    if(N) scanf("%lld/%lld", &result.up, &result.down);
    for(int i=1; i<N; i++)
    {
        scanf("%lld/%lld", &A.up, &A.down);
        B = result;//B暂存其中一个数据
        result.down = A.down*B.down;//按数学规律进行相加
        result.up = A.up*B.down + A.down*B.up;
        result = reduction(result);
    }
    if(result.down == 1) printf("%lld", result.up);//输出注意区分整数、假分数和真分数
    else if(result.up > result.down) printf("%lld %lld/%lld", result.up/result.down, result.up%result.down, result.down);
    else printf("%lld/%lld", result.up, result.down);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/86592707