样例(可复制)
2/3 -4/2
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
5/3 0/6
1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf
提供1个易错样例
1/3 -1/2
1/3 + (-1/2) = (-1/6)
1/3 - (-1/2) = 5/6
1/3 * (-1/2) = (-1/6)
1/3 / (-1/2) = (-2/3)
注意点
- 除法分母为0时应该进行特判输出Inf。
- 负数无需特殊处理,只需当作分子为负数的分数即可。如果采用其他写法,那么需要注意负分数的输出。
- 数据范围为int, 因此两个分母相乘时,最大可以达到long long,所以如果使用int就会溢出,得到“答案错误”。
- 计算最大公约数时,要注意是计算分子分母绝对值的公约数。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int gcd(ll a,ll b){
return b==0?a:gcd(b,a%b);
}
void show(ll a,ll b){
ll d=gcd(abs(a),b);
a/=d;
b/=d;
if(b<0){a=-a;b=-b;
}
if(a<0)cout<<"(";
if(b==1){
cout<<a;
}else if(abs(a)>b){
cout<<a/b<<" "<<abs(a)%b<<"/"<<b;
}else cout<<a<<"/"<<b;
if(a<0)cout<<")";
}
void add(ll a1,ll b1,ll a2,ll b2){
show(a1,b1);
cout<<" + ";
show(a2,b2);
a1=a1*b2+a2*b1;
b1=b1*b2;
cout<<" = ";
show(a1,b1);
cout<<endl;
}
void sub(ll a1,ll b1,ll a2,ll b2){
show(a1,b1);
cout<<" - ";
show(a2,b2);
a1=a1*b2-a2*b1;
b1=b1*b2;
cout<<" = ";
show(a1,b1);
cout<<endl;
}
void mul(ll a1,ll b1,ll a2,ll b2){
show(a1,b1);
cout<<" * ";
show(a2,b2);
a1=a1*a2;
b1=b1*b2;
cout<<" = ";
show(a1,b1);
cout<<endl;
}
void div(ll a1,ll b1,ll a2,ll b2){
show(a1,b1);
cout<<" / ";
show(a2,b2);
a1=a1*b2;
b1=b1*a2;
cout<<" = ";
if(b1==0)cout<<"Inf";
else show(a1,b1);
cout<<endl;
}
int main(){
ll a1,b1,a2,b2;
scanf("%lld/%lld %lld/%lld",&a1,&b1,&a2,&b2);
add(a1,b1,a2,b2);
sub(a1,b1,a2,b2);
mul(a1,b1,a2,b2);
div(a1,b1,a2,b2);
return 0;
}