PAT 甲级 1088 Rational Arithmetic
作者:互联网
PAT 甲级 1088 Rational Arithmetic
大家注意一下Inf不要写成INF不然就会像个憨批一样扒数据扒半个小时。
#include <bits/stdc++.h>
using namespace std;
struct Fraction {
long long up, down;
};
long long gcd(long long a, long long b)
{
if (b == 0) return a;
while (a != 0) {
if (b > a) swap(a, b);
a %= b;
}
return b;
}
Fraction Reduction(Fraction f)
{
// 分母为0的情况没有处理,调用时注意
// 规整符号
if (f.down < 0) {
f.up = -f.up;
f.down = -f.down;
}
// 分子为0
if (f.up == 0)
f.down = 1;
else {
int d = gcd(abs(f.up), abs(f.down));
f.up /= d;
f.down /= d;
}
return f;
}
Fraction Add(Fraction a, Fraction b)
{
Fraction ans;
ans.down = a.down * b.down;
ans.up = a.up * b.down + a.down * b.up;
return Reduction(ans);
}
Fraction Minu(Fraction a, Fraction b)
{
Fraction ans;
ans.down = a.down * b.down;
ans.up = a.up * b.down - a.down * b.up;
return Reduction(ans);
}
Fraction Multi(Fraction a, Fraction b)
{
Fraction ans;
ans.down = a.down * b.down;
ans.up = a.up * b.up;
return Reduction(ans);
}
Fraction Divide(Fraction a, Fraction b)
{
Fraction ans;
ans.down = a.down * b.up;
ans.up = a.up * b.down;
return Reduction(ans);
}
void Print(Fraction f)
{
f = Reduction(f);
if (f.up < 0) printf("(");
// 整数
if (f.down == 1)
printf("%lld", f.up);
// 假分数
else if (abs(f.up) > abs(f.down))
printf("%lld %lld/%lld", f.up / f.down, abs(f.up) % f.down, f.down);
// 真分数
else
printf("%lld/%lld", f.up, f.down);
if (f.up < 0) printf(")");
}
int main()
{
Fraction a, b;
scanf("%lld/%lld %lld/%lld", &a.up, &a.down, &b.up, &b.down);
// 加
Print(a);
cout << " + ";
Print(b);
cout << " = ";
Print(Add(a, b));
cout << endl;
// 减
Print(a);
cout << " - ";
Print(b);
cout << " = ";
Print(Minu(a, b));
cout << endl;
// 乘
Print(a);
cout << " * ";
Print(b);
cout << " = ";
Print(Multi(a, b));
cout << endl;
// 除
Print(a);
cout << " / ";
Print(b);
cout << " = ";
if (b.up != 0)
Print(Divide(a, b));
else
printf("Inf");
cout << endl;
}
标签:PAT,Rational,up,long,down,Fraction,ans,Arithmetic,lld 来源: https://blog.csdn.net/u011917745/article/details/116197514