分数相加and化简——PAT (Advanced Level) 1081 Rational Sum (20 分)

分数相加and化简——PAT (Advanced Level) 1081 Rational Sum (20 分)
题目概要:
给若干个分数,求其和,并化简成带分数形式

题目分析:
1.gcd最大公因数(凭感觉写记得abs,然后测试一下)
2.cal计算两分数之和,用curup和curdown记录
3.最终根据curup和curdown的%关系以及/关系还有是否带分数整数为0关系进行输出

完整代码:

#include<bits/stdc++.h>
using namespace std;

long long curup, curdown;
//找最大公因数
long long gcd(long long x, long long y)
{   
    x = abs(x);
    y = abs(y);
    if(x % y == 0) return y;
    if(y % x == 0) return x;
    if(x >= y) return gcd(y, y - x % y);
    else return gcd(x, x - y % x);
}

//两两计算
void cal(long long a, long long b, long long c, long long d)
{   
    long long up = a * d + b * c;
    long long down = b * d;
    if(a == 0)
    {
        up = c;
        down = d;
    }
    if(c == 0)
    {
        up = a;
        down = b;
    }
    long long com = gcd(up, down);
    curup = up / com;
    curdown = down / com;
}


int main()
{
    //cout << gcd(0,16) << endl;
    int n;
    scanf("%d", &n);
    long long a, b;
    scanf("%lld/%lld", &curup, &curdown);
    for(int i = 1; i < n; i++)
    {
        scanf("%lld/%lld", &a, &b);
        //cout << curup << " " << curdown << " " << a << " " << b << endl;
        cal(curup, curdown, a, b);
    }
    //cal(-1, 2, 1, 8);
    //cout << curup << " " << curdown << endl;
    if(curup < 0) cout << "-";
    curup = abs(curup);
    if(curup % curdown == 0) 
    {
        cout << curup / curdown << endl;
        return 0;
    }
    else
    {   
        if(curup / curdown != 0)
            cout << curup / curdown << " " << curup - curdown * (curup / curdown) << "/" << curdown << endl;
        else 
            cout << curup << "/" << curdown << endl;
        return 0;
    }
}

总结:
看好题设,说好的longlong就不要int了

上一篇:2021杭电多校赛第七场


下一篇:奇怪的电梯