标签:PAT Rational up long down Fraction ans Arithmetic lld
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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。