• PAT甲级——A1081 Rational Sum


    Given N rational numbers in the form numerator/denominator, you are supposed to calculate their sum.

    Input Specification:

    Each input file contains one test case. Each case starts with a positive integer N (≤), 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.

    Output Specification:

    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.

    Sample Input 1:

    5
    2/5 4/15 1/30 -2/60 8/3
    

    Sample Output 1:

    3 1/3
    

    Sample Input 2:

    2
    4/3 2/3
    

    Sample Output 2:

    2
    

    Sample Input 3:

    3
    1/3 -1/6 1/8
    

    Sample Output 3:

    7/24
     1 #include <iostream>
     2 #include <vector>
     3 #include <math.h>
     4 using namespace std;
     5 long int  gcd(long int a, long int b)
     6 {
     7     if(b==0) return a;
     8     else return gcd(b,a%b);    
     9 }
    10 int main()
    11 {
    12     int N;
    13     cin >> N;
    14     long long Inter = 0, resa = 0, resb = 1, a, b, Div, Mul;
    15     for (int i = 0; i < N; ++i)
    16     {
    17         char c;
    18         cin >> a >> c >> b;
    19         resa = resa * b + a * resb;//同分相加的分子
    20         resb = resb * b;
    21         Inter += resa / resb;//简化
    22         resa = resa - resb * (resa / resb);
    23         Div = gcd(resb, resa);
    24         resa /= Div;
    25         resb /= Div;
    26     }
    27     if (Inter == 0 && resa == 0)
    28         cout << 0 << endl;
    29     else if (Inter != 0 && resa == 0)
    30         cout << Inter << endl;
    31     else if (Inter == 0 && resa != 0)
    32         cout << resa << "/" << resb << endl;
    33     else
    34         cout << Inter << " " << resa << "/" << resb << endl;
    35     return 0;
    36 }
  • 相关阅读:
    2021.2.28
    《构建之法》11~16章读后感
    《构建之法》6~10章读后感
    《构建之法》1~5章读后感
    4.7 wait notify
    4.8 wait,notify 的正确姿势
    4.9 park&unpark
    4.10 重新理解线程的状态转换
    第七章 Redis-6.2.1脚本安装
    第三十九章 Centos 7 系统优化脚本
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11326646.html
Copyright © 2020-2023  润新知