美文网首页
PAT甲级(Advanced Level)练习题——1001

PAT甲级(Advanced Level)练习题——1001

作者: 制冷少年徐同学 | 来源:发表于2017-08-19 17:59 被阅读0次

    从今天开始刷题 =。=
    会经常更新的

    题目描述
    Given N rational numbers in the form "numerator/denominator", you are supposed to calculate their sum.

    输入描述:
    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.

    输出描述:
    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.

    输入例子:
    5
    2/5 4/15 1/30 -2/60 8/3

    输出例子:
    3 1/3

    代码:

    #include <iostream>
    using namespace std;
    
    // 辗转相除
    long long gcd(long long a, long long b)
    {
        if(0 == b) return a;
        else return gcd(b, a%b);
    }
    
    int main()
    {
        // freopen("input.txt", "r", stdin);
    
        int num = 0;
        cin >> num;
    
        long int numerators[100];
        long int denominator[100];
    
        // 通分并相加
        long long product = 1, sum = 0;
    
        for (int i=0; i<num; i++)
        {
            char ctemp = 0;
            cin >> numerators[i] >> ctemp >> denominator[i];
            product *= denominator[i];
        }
    
        for (int i=0; i<num; i++)
        {
            sum += (numerators[i] * product / denominator[i]);
        }
    
        // 约分
        auto temp = abs(gcd(sum, product));
        sum /= temp;
        product /= temp;
    
        if (0 == sum%product)   // 整除
        {
            cout << sum/product << endl;
        }
        else if (abs(sum)>product)  // 带分数
        {
            cout << sum/product << " " << sum%product << "/" << product << endl;
        }
        else cout << sum << "/" << product << endl; // 真分数
    
        return 0;
    }
    

    Tips:
    1.gcd求出的最大公约数可能为负值,需要判断

    相关文章

      网友评论

          本文标题:PAT甲级(Advanced Level)练习题——1001

          本文链接:https://www.haomeiwen.com/subject/ohotdxtx.html