1. 程式人生 > >PAT乙級 1034

PAT乙級 1034

思路:是個水題,但是有坑。不能被題目忽悠了,題目保證正確的輸出中沒有超過整型範圍的整數。 它只是保證結果不超出int,但是我們在運算過程中的乘法可能會超出int,直接把所有int改成long long

AC程式碼

#include <stdio.h>
#include <algorithm>
using namespace std;
typedef long long LL;

LL a, b, c, d;
LL e, f, g, h;

LL gcd(LL a, LL b) {
    return b == 0 ? a : gcd(b, a%b);
}

void kill
(LL &a, LL &b, LL &e, LL &f) { if(b == 0) { printf("Inf"); return; } if(a == 0) { printf("0"); e = 0, f = 1; return; } else { LL r = gcd(a, b); e = a / r, f = b / r; } LL l = abs(e) / abs(f); LL p = abs(e) - l * abs
(f); if(e < 0 || f < 0) { printf("("); } if(e < 0 || f < 0) { printf("-"); } //output if(l != 0) printf("%d", l); if(l != 0 && p != 0) printf(" "); if(p != 0) { printf("%d/%d", p, abs(f)); } if(e < 0 || f < 0) { printf
(")"); } } void add() { kill(a, b, e, f); printf(" + "); kill(c, d, g, h); printf(" = "); LL p = f*h / gcd(f, h); LL res = e * (p/f) + g * (p/h); kill(res, p, res, p); printf("\n"); } void sub() { kill(a, b, e, f); printf(" - "); kill(c, d, g, h); printf(" = "); LL p = f*h / gcd(f, h); LL res = e * (p/f) - g * (p/h); kill(res, p, res, p); printf("\n"); } void mul() { kill(a, b, e, f); printf(" * "); kill(c, d, g, h); printf(" = "); LL res = e * g; LL p = f * h; kill(res, p, res, p); printf("\n"); } void div() { kill(a, b, e, f); printf(" / "); kill(c, d, g, h); printf(" = "); LL res = e * h; LL p = f * g; kill(res, p, res, p); printf("\n"); } int main() { while(scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d) != EOF) { add(); sub(); mul(); div(); } return 0; }

如有不當之處歡迎指出!