b538. 分數運算-2

解法一

✅ 完整代碼

評分結果(參考) : AC (2ms, 352KB)

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

void printAns(int x, int y){
    if(x == 0){
        cout << "0\n";
    }
    else if(y != 1 && y != -1){
        
        if((x<0) ^ (y<0)) cout << "-";
        cout << abs(x) << "/" << abs(y) << "\n";
    }
    else{
        if((x<0) ^ (y<0)) cout << "-";
        cout << abs(x) << "\n";
    }
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int a, b, c, d;
    char op;
    while(cin >> a >> b >> c >> d >> op){
        // a/b op c/d
        int x, y;
        if(op == '+'){
            x = a*d + c*b;
            y = b*d;
        }
        else if(op == '-'){
            x = a*d - c*b;
            y = b*d;
        }
        else if(op == '*'){
            x = a*c;
            y = b*d;
        }
        else if(op == '/'){
            x = a*d;
            y = b*c;
        }
        
        int g = __gcd(x, y);
        printAns(x/g, y/g);
    }
    
    return 0;
}