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 <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求出的最大公约数可能为负值,需要判断

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 时常担心老去的问题于是担心凋谢的季节来到担心花自飘零水自流然后夜晚缓缓降落就淹没在夜色中缄默着呼吸沉重灵魂却向上升...
    老实人艾伦阅读 1,423评论 0 1
  • 开心, 自参观了丘吉尔庄园后, 你对英国的贵族和皇族 有了概念 所以当来到温莎城堡时 似乎并没有很陌生 女王老奶奶...
    蔡敏_Michelle阅读 1,427评论 0 0
  • 被大雨淋湿别哭 虽然眼角的泪水一直止不住的流 一路奔跑在大雨倾盆的夜 只为回家 开门进屋 拿起毛巾把头发擦干 换上...
    玫瑰西海岸阅读 1,549评论 0 0

友情链接更多精彩内容