PAT甲級(jí)(Advanced Level)練習(xí)題——1001

從今天開始刷題 =。=
會(huì)經(jīng)常更新的

題目描述
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;

// 輾轉(zhuǎn)相除
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)  // 帶分?jǐn)?shù)
    {
        cout << sum/product << " " << sum%product << "/" << product << endl;
    }
    else cout << sum << "/" << product << endl; // 真分?jǐn)?shù)

    return 0;
}

Tips:
1.gcd求出的最大公約數(shù)可能為負(fù)值,需要判斷

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 時(shí)常擔(dān)心老去的問題于是擔(dān)心凋謝的季節(jié)來到擔(dān)心花自飄零水自流然后夜晚緩緩降落就淹沒在夜色中緘默著呼吸沉重靈魂卻向上升...
    老實(shí)人艾倫閱讀 187評(píng)論 0 1
  • 開心, 自參觀了丘吉爾莊園后, 你對(duì)英國(guó)的貴族和皇族 有了概念 所以當(dāng)來到溫莎城堡時(shí) 似乎并沒有很陌生 女王老奶奶...
    蔡敏_Michelle閱讀 163評(píng)論 0 0
  • 被大雨淋濕別哭 雖然眼角的淚水一直止不住的流 一路奔跑在大雨傾盆的夜 只為回家 開門進(jìn)屋 拿起毛巾把頭發(fā)擦干 換上...
    玫瑰西海岸閱讀 217評(píng)論 0 0