这个题目关键是写一个化简函数,测试点3和4考察的是 对负数的处理
测试点4不能用 a*b<0判断 负数,因为会溢出。
测试点3就是分母为负数的情况。
附本人AC代码:
#include<iostream>
#include<string>
#include<math.h>
using namespace std;
long long gcd(long long A, long long B) {
return B == 0 ? A : gcd(B,A%B);
}
string simply(long long a, long long b) {
bool flag = false;
string s;
if ((long long)a*(long long)b<(long long)0) {
a = abs(a);
b = abs(b);
flag = true;
s += "(-";
}
if (a == 0)return "0";
long long t = gcd(a, b);
a /= t;
b /= t;
t = a / b;
if (t > 0) {
s += to_string(t);
a -= t * b;
}
if (a > 0) {
if (t>0)s += " ";
s +=to_string(a) + "/" + to_string(b);
}
if (flag)s += ")";
return s;
}
int main() {
long long f1, f2, m1, m2;
scanf("%lld/%lld %lld/%lld", &f1, &m1, &f2, &m2);
cout << simply(f1, m1) + " + " + simply(f2, m2) + " = " + simply(f1*m2 + f2 * m1, m1*m2) << endl;
cout << simply(f1, m1) + " - " + simply(f2, m2) + " = " + simply(f1*m2 - f2 * m1, m1*m2) << endl;
cout << simply(f1, m1) + " * " + simply(f2, m2) + " = " + simply(f1*f2, m1*m2) << endl;
if (abs(f2) == 0)cout << simply(f1, m1) + " / " + simply(f2, m2) + " = Inf";
else cout << simply(f1, m1) + " / " + simply(f2, m2) + " = "+simply(f1*m2, f2*m1);
return 0;
}