解题代码
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
struct fraction {
ll up, down;
}a, b;
typedef struct fraction fra;
ll gcd(ll a, ll b) {
return !b ? a : gcd(b, a%b);
}
fra Reduction(fra a) {
if (a.down < 0) {
a.up = -a.up;
a.down = -a.down;
}
if (a.up == 0) a.down = 1;
else {
int d = (int)gcd(abs(a.up), abs(a.down));
a.up /= d;
a.down /= d;
}
return a;
}
void Print(fra a) {
if (a.up < 0) printf("(");
if (a.down == 1) printf("%lld", a.up);
else if (abs(a.up) > a.down) printf("%lld %lld/%lld", a.up / a.down, abs(a.up) % a.down, a.down);
else printf("%lld/%lld", a.up, a.down);
if (a.up < 0) printf(")");
}
fra Add(fra a, fra b) {
fra ret;
ret.up = a.up*b.down + a.down*b.up;
ret.down = a.down*b.down;
return ret;
}
fra Sub(fra a, fra b) {
fra ret;
ret.up = a.up*b.down - a.down*b.up;
ret.down = a.down*b.down;
return ret;
}
fra Mul(fra a, fra b) {
fra ret;
ret.up = a.up*b.up;
ret.down = a.down*b.down;
return ret;
}
fra De(fra a, fra b) {
fra ret;
ret.up = a.up*b.down;
ret.down = a.down*b.up;
return ret;
}
int main() {
scanf("%lld/%lld %lld/%lld", &a.up, &a.down, &b.up, &b.down);
a = Reduction(a);
b = Reduction(b);
char sym[4] = { '+','-','*','/' };
for (int i = 0; i < 4; i++) {
Print(a);
printf(" %c ", sym[i]);
Print(b);
printf(" = ");
fra ret;
switch (sym[i])
{
case '+':ret = Add(a, b); break;
case '-':ret = Sub(a, b); break;
case '*':ret = Mul(a, b); break;
case '/':ret = De(a, b); break;
}
if (ret.down == 0) printf("Inf");
else Print(Reduction(ret));
printf("\n");
}
return 0;
}
测试结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/41a17d85b16efc290a20f34a521fd67d.png)
问题整理
1.分数四则运算。
2.注意int溢出。
3.注意输出的分类:整数、假分数、真分数。
4.利用algorithm的abs代替cmath的fabs,因为pat不支持cmath的abs,我也不到为啥。