• PAT 甲级 1081 Rational Sum (20分)(多个分式相加,gcd忘了)*


    1081 Rational Sum (20分)
     

    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

    题意:
    给N个有理数(以分⼦/分⺟的形式给出),计算这N个数的总和,最后总和要以(整数 分⼦/分⺟)的形式给出~没整数就不给整数,分子是0,就不给分数
    题解:

      先根据分数加法的公式累加,后分离出整数部分和分数部分分⼦和分⺟都在⻓整型内,所以不能⽤int存储,否则有⼀个测试点不通过⼀开始⼀直是浮点错误,按理来说应该是出现了/0或者%0的情况,找了半天也不知道错在哪⾥,后来注意到应该在累加的时候考虑是否会超出long long的范围,所以在累加每⼀步之前进⾏分⼦分⺟的约分处理,然后就AC了~

         最小公倍数,最小公因数的gcd有点忘记了,回来要复习呀~

    AC代码:
    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    ll a;
    ll b;
    int n;
    ll gcd(ll x,ll y){
        return y == 0 ? x : gcd(y , x % y);
    }
    int main(){
        cin>>n;
        char c;
        ll fenzi=0;//初始化 
        ll fenmu=1;
        for(int i=1;i<=n;i++){
            cin>>a>>c>>b;
            if(b<0){//分母<0特殊处理 
                a=-1*a;
                b=-1*b;
            }
            ll gc=gcd(fenmu,b);
            fenzi = fenzi*b*gc + a*fenmu*gc;//先分子,再分母 
            fenmu=fenmu*b*gc;
            gc=gcd(fenmu,fenzi);//要通分,否则会爆ll浮点错误 
            fenmu/=gc;
            fenzi/=gc;
        }
        ll zheng = fenzi/fenmu;
        fenzi = fenzi%fenmu;
        if(fenzi==0) cout<<zheng;
        else{
            if(zheng==0){
                cout<<fenzi<<"/"<<fenmu;
            }else{
                cout<<zheng<<" ";
                cout<<fenzi<<"/"<<fenmu;
            }
        } 
        return 0;
    } 


  • 相关阅读:
    mysql主从备份案例—读写分离(异步主从)
    MySQL 汉化+完全备份操作实例
    Linux指令和shell脚本
    文件压缩和打包
    文件系统格式化和挂载
    linux常用指令和一些选项的汇总
    linux文件权限和群组
    [windows][技巧]百度网盘提示您的电脑已安装百度网盘,是否覆盖,解决方法
    [html][js]视频倍速播放功能
    [julia][学习笔记]julia的安装
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/13270564.html
Copyright © 2020-2023  润新知