• PAT-Rational Sum (20)


    题目描述

    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


    要注意一些坑,比如最大公因数如果为负数要取反,确保负号在分子上。
    结果sum为0时输出0;分子小于分母,结果的分子为分母整数倍数部分为空;求和的分子如果为分母的整数倍,则分数部分为空;
    #include<bits/stdc++.h>
    using namespace std;
    
    typedef long long ll;
    ll a[110], b[110];
    int main()
    {
        //freopen("in.txt", "r", stdin);
        int N;
        scanf("%d", &N);
        scanf("%lld/%lld", &a[0], &b[0]);
        ll minn = b[0];
        int gcd;
        for (int i = 1; i < N; ++i)
        {
            scanf("%lld/%lld", &a[i], &b[i]);
            gcd = __gcd(minn, b[i]);
            if (gcd < 0)gcd = -gcd;
            minn = minn / gcd * b[i];
        }
        ll sum = 0;
        for (int i = 0; i < N; i++)
        {
            a[i] = minn / b[i] * a[i];
            sum += a[i];
        }
        if (sum == 0) {printf("0"); return 0;}
        ll num = sum / minn;
        sum = sum - num * minn;
        //cout<<sum<<endl;
        if (sum != 0)
        {
            ll k = __gcd(sum, minn);
            if(k<0)k=-k;
            minn /= k;
            sum /= k;
        }
        //cout<<sum<<endl;
        if (sum == 0)
        {
            if (num != 0)
                printf("%lld
    ", num);
            // else
            // printf("0");
        }
        else
        {
            if (num != 0)
                printf("%lld %lld/%lld
    ", num, sum, minn);
            else
                printf("%lld/%lld
    ", sum, minn);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    树莓派笔记——了解与购买树莓派(1)
    SQLserver 备份和还原 失败
    lua coroutine
    lua for循环
    leetcode 46. 全排列
    sprintf、vsprintf、sprintf_s、vsprintf_s、_snprintf、_vsnprintf、snprintf、vsnprintf 函数辨析
    rapidxml的常见读写操作
    C++11 可变参数模板构造string列表
    Fedora 28 设置yum代理
    Linux命令计算文件中某一列的平均值
  • 原文地址:https://www.cnblogs.com/kuroko-ghh/p/10268744.html
Copyright © 2020-2023  润新知