https://pintia.cn/problem-sets/994805260223102976/problems/994805287624491008
测试点3是要改 int 为 long long 类型。测试点2一直都无法通过,百度了好多次都没找到解决方法。
最终看到这个链接的内容,发现是正负号的问题,因为一开始我的 sign 是靠 a*b 的积来判断的,不知道为什么会出错,可能是编译器的问题。
还有最大公约数的求法,是欧几里德算法,也叫辗转相除法。
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
// 最大公约数
long long gcd(long long a,long long b){
long long t=0;
while(b!=0){
t=a%b;
a=b;
b=t;
}
return a;
}
// 递归版
// int gcd(int a,int b){
// return b==0 ? a : gcd(b, a%b);
// }
string simplfy(long long a, long long b){
string str;
// 如果分母or分子为0
if(b == 0) return "Inf";
if(a == 0) return "0";
// 下面的写法无法通过测试点2
// int sign = a*b<0 ? -1 : 1;
// 如果分子or分母为负
int sign = 1;
if(a<0)
sign *= -1;
if(b<0)
sign *= -1;
a = abs(a);
b = abs(b);
// 找最大公约数进行约分
long long divisor = gcd(a, b);
a = a / divisor;
b = b / divisor;
// 有整数部分
if(a/b!=0){
str += to_string(a/b);
if(a%b!=0)// 没被整除
str += " " + to_string(a%b) + "/" + to_string(b);
}else// 没整数部分
str += to_string(a) + "/" + to_string(b);
// 如果是负数
if(sign<0)
str = "(-"+str+")";
return str;
}
int main() {
long long a1, b1, a2, b2;
string str1, str2, res;
scanf("%lld/%lld %lld/%lld", &a1, &b1, &a2, &b2);
str1 = simplfy(a1, b1);
str2 = simplfy(a2, b2);
// 加
res = simplfy(a1*b2+a2*b1, b1*b2);
cout << str1 << " + " << str2 << " = " << res << endl;
// 减
res = simplfy(a1*b2-a2*b1, b1*b2);
cout << str1 << " - " << str2 << " = " << res << endl;
// 乘
res = simplfy(a1*a2, b1*b2);
cout << str1 << " * " << str2 << " = " << res << endl;
// 除
res = simplfy(a1*b2, b1*a2);
cout << str1 << " / " << str2 << " = " << res << endl;
return 0;
}