#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long ll;
class Fraction {
public:
ll up, down;
bool isInf;
Fraction(ll x = 0, ll y = 1) {
up = x;
down = y;
isInf = false;
this->reduction();
}
Fraction operator+(const Fraction& x) {
Fraction res;
res.up = this->up*x.down + this->down*x.up;
res.down = this->down*x.down;
res.reduction();
return res;
}
Fraction operator-(const Fraction& x) {
Fraction res;
res.up = this->up*x.down - this->down*x.up;
res.down = this->down*x.down;
res.reduction();
return res;
}
Fraction operator*(const Fraction& x) {
Fraction res;
res.up = this->up*x.up;
res.down = this->down*x.down;
res.reduction();
return res;
}
Fraction operator/(const Fraction& x) {
Fraction res;
res.up = this->up*x.down;
res.down = this->down*x.up;
if (res.down != 0) {
res.reduction();
}
else {
res.isInf = true;
}
return res;
}
//显示分数 4种情况
void showFraction() {
if (this->isInf) { // 分母为0
printf("Inf");
return;
}
//if (this->up < 0)printf("(");
if (this->down == 1) { // 整数
printf("%lld", this->up);
}
else if (abs(this->up) > abs(this->down)) { //假分数:分子>分母
printf("%lld %lld/%lld", this->up / this->down, abs(this->up) % abs(this->down), this->down);
}
else { //真分数:分子<分母
printf("%lld/%lld", this->up, this->down);
}
//if (this->up < 0)printf(")");
//printf("\n");
}
//显示小数
void showFloat() {
printf("%f\n", (double)this->up*1.0 / this->down);
}
ll getGcd(ll x, ll y) { // 辗转相除法求最大公约数
if (y == 0)return x;
else return getGcd(y, x%y);
}
void reduction() { // 化简
if (this->down < 0) { // 如果分母小于0,则分子分母都取相反数
this->up = -this->up;
this->down = -this->down;
}
if (this->up == 0) { //如果分子为0,则令分母为1,方便输出函数处理
this->down = 1;
}
else { //分子分母除以他们的最大公约数
ll gcd = getGcd(abs(this->up), abs(this->down));
this->up /= gcd;
this->down /= gcd;
}
}
};
//对分数进行加减乘除运算
int main() {
int n, up, down;
Fraction x, y, z;
char select[4] = { '+','-','*','/' };
scanf("%lld/%lld %lld/%lld", &x.up, &x.down, &y.up, &y.down);
x.reduction();
y.reduction();
for (int op = 0; op < 4; op++) {
switch (op)
{
case 0:
z = x + y;
break;
case 1:
z = x - y;
break;
case 2:
z = x * y;
break;
case 3:
z = x / y;
break;
}
x.showFraction();
printf(" %c ", select[op]);
y.showFraction();
printf(" = ");
z.showFraction();
printf("\n");
}
return 0;
}
以下是PAT的样例数据
Sample Input 1:
2/3 -4/2
Sample Output 1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
Sample Input 2:
5/3 0/6
Sample Output 2:
1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf