PAT甲级1081 Rational Sum

1081

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 (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.

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
结尾无空行

折磨点请看代码里的注解:(出错测试点3)
总结就是尽量用最大的、不会溢出的类型存储数据

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
long long gcd(long long a,long long b){
    return b == 0?a:gcd(b,a % b);
}

void isout(long long a,long long b){
    if(abs(a) < b){
        cout << a << '/' << b << endl; 
        return;
    }
    long long c = 0;
    c = a / b;
    a %= b;
    if(a == 0){
        cout << c << endl;
    }
    else{
        cout << c << ' ' << a << '/' << b << endl;
    }
    return;
}

int main(){
    int n;
    cin >> n;
    vector<int> numerator;
    vector<int> denominator;
    for(int i = 0;i < n;++i){
        int k,l;
        scanf("%d/%d",&k,&l);
        if(k == 0||l == 0){
            continue;
        }
        else{
            numerator.push_back(k);
            denominator.push_back(l);
        }
    }
    int len = numerator.size();
    ///
    long long a = numerator[0],b = denominator[0];
    //
    for(int i = 1;i < len;++i){
    //测试点出错的情况是c和d设置为int时a和b设置为long long
    //会出错,其余情况包括将数组改为int也是一样不会出错,
    //不知道为什么,只能默认用最大的存储方式存储了
        long long c = numerator[i],d = denominator[i];
        //
        a = a * d / gcd(b,d);
        c = c * b / gcd(b,d);
        a += c;
        b = b * d / gcd(b,d);
    }
    if(a == 0){
        cout << 0 << endl;
    }
    else{
        long long temp = gcd(abs(a),b);
        a /= temp;
        b /= temp;
        isout(a,b);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值