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

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

题目描述
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 
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> numerators[i] >> ctemp >> denominator[i];
        product *= denominator[i];
    }

    for (int i=0; iproduct)  // 带分数
    {
        cout << sum/product << " " << sum%product << "/" << product << endl;
    }
    else cout << sum << "/" << product << endl; // 真分数

    return 0;
}

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

你可能感兴趣的:(PAT甲级(Advanced Level)练习题——1001)