1088 Rational Arithmetic
Posted CSU迦叶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1088 Rational Arithmetic相关的知识,希望对你有一定的参考价值。
本题需要具备有理数处理相关知识。
本次收获(错点)
(1)在化简求最大公约数时,忘记给传入的分子加绝对值
(2)把除法错写成乘法,自己设计测试用例才测出orz
AC代码
#include<cstdio>
#include<iostream>
#include<set>
#include<vector>
#include<map>
#include<algorithm>
#include<cmath>
#include<queue>
#include<string>
using namespace std;
const int maxn = 1001;
typedef long long ll;
struct Frac{
ll up,down;
};
ll gcd(ll a,ll b){
return b==0?a:gcd(b,a%b);
}
Frac reduct(Frac bn){
if(bn.down<0){
bn.up = -bn.up;
bn.down = -bn.down;
}
if(bn.up==0)bn.down = 1;
// else{
ll shared = gcd(abs(bn.up),bn.down);
bn.up /= shared;
bn.down /= shared;
// }
return bn;
}
void print(Frac bn){
bn = reduct(bn);
if(bn.up<0)printf("(");
if(bn.down==1){
printf("%lld",bn.up);
}else if(abs(bn.up)>bn.down){
printf("%lld %lld/%lld",bn.up/bn.down,abs(bn.up)%bn.down,bn.down);
}else{
printf("%lld/%lld",bn.up,bn.down);
}
if(bn.up<0)printf(")");
}
Frac addBign(Frac a,Frac b){
Frac c;
c.up = a.up*b.down + b.up*a.down;
c.down = a.down*b.down;
return reduct(c);
}
Frac subBign(Frac a,Frac b){
Frac c;
c.up = a.up*b.down - b.up*a.down;
c.down = a.down*b.down;
return reduct(c);
}
Frac multiBign(Frac a,Frac b){
Frac c;
c.up = a.up*b.up;
c.down = a.down*b.down;
return reduct(c);
}
Frac diviBign(Frac a,Frac b){
Frac c;
c.up = a.up*b.down;
c.down = a.down*b.up;
return reduct(c);
}
int main(){
Frac a,b;
scanf("%lld/%lld %lld/%lld",&a.up,&a.down,&b.up,&b.down);
print(reduct(a));
printf(" + ");
print(reduct(b));
printf(" = ");
print(addBign(a,b));
printf("\\n");
print(reduct(a));
printf(" - ");
print(reduct(b));
printf(" = ");
print(subBign(a,b));
printf("\\n");
print(reduct(a));
printf(" * ");
print(reduct(b));
printf(" = ");
print(multiBign(a,b));
printf("\\n");
print(reduct(a));
printf(" / ");
print(reduct(b));
printf(" = ");
if(b.up!=0)print(diviBign(a,b));
else printf("Inf");
return 0;
}
以上是关于1088 Rational Arithmetic的主要内容,如果未能解决你的问题,请参考以下文章
A.1088 Rational Arithmetic (20)
1088. Rational Arithmetic (20)——PAT (Advanced Level) Practise