随手练——分式计算

  除了分子为1,为0的情况,还有要注意的就是对不同的运算,不同的输入,负号可能在不同的位置,按道理来说,负数符号应该写在分子。题目没说清楚负号写哪儿,要么就是测试数据根本不会触及到负数,要么就是出题人没考虑到,诅咒出题人vbhsdvbkjsdvadb,题目没说 还是不做处理的好,写了说不定反而会错。

  像这个题目,测试数据给的很清楚,符号写在分子上:https://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Index/problemdetail/pid/3849.html

但是这个题目没有考虑为分子为0的情况(我把分子为0那一段注释了,交也AC了),对,我就是魔鬼。

#include <iostream>

using namespace std;
typedef long long ll;
ll gcd(ll a, ll b) {
    return b ? gcd(b, a%b) : a;
}
ll lcm(ll a, ll b) {
    return a / gcd(a, b)*b;
}
void reduction(ll &a, ll &b) {
    ll t = gcd(a, b);
    a /= t; b /= t;
}

void add(ll &a1, ll &b1, ll &a2, ll &b2) {
    ll x = lcm(b1, b2);
    a1 = a1 * (x / b1) + a2 * (x / b2);
    b1 = x;
    reduction(a1, b1);
}
void sub(ll &a1, ll &b1, ll &a2, ll &b2) {
    ll x = lcm(b1, b2);
    a1 = a1 * (x / b1) - a2 * (x / b2);
    b1 = x;
    reduction(a1, b1);
}

void mul(ll &a1, ll &b1, ll &a2, ll &b2) {
    a1 *= a2;
    b1 *= b2;
    reduction(a1, b1);
}

void divide(ll &a1, ll &b1, ll &a2, ll &b2) {
    a1 *= b2;
    b1 *= a2;
    reduction(a1, b1);
}
int main() {
    ll x1, y1, x2, y2;
    char symbol;
    while (~scanf("%lld/%lld%c%lld/%lld", &x1, &y1, &symbol, &x2, &y2)){

        switch (symbol)
        {
        case '+':add(x1, y1, x2, y2);
            break;
        case '-':sub(x1, y1, x2, y2);
            break;
        case '*':mul(x1, y1, x2, y2);
            break;
        case '/':
            case '\\':
                divide(x1, y1, x2, y2);
            break;
        default:
            break;
        }
        if (y1 < 0) {
            x1 = -x1; y1 = -y1;
        }
        if (y1 == 1)
            cout << x1 << endl;
        else if (y1 == 0)
            cout << 0 << endl;
        else
            cout << x1 << "/" << y1 << endl;
    }
    return 0;
}

 

posted @ 2019-01-15 09:19  czc1999  阅读(69)  评论(0编辑  收藏  举报