1034 有理数四则运算
作者:互联网
本题要求编写程序,计算 2 个有理数的和、差、积、商。
输入格式:
输入在一行中按照 a1/b1 a2/b2 的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分母不为 0。
输出格式:
分别在 4 行中按照 有理数1 运算符 有理数2 = 结果 的格式顺序输出 2 个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的最简形式 k a/b,其中 k 是整数部分,a/b 是最简分数部分;若为负数,则须加括号;若除法分母为 0,则输出 Inf。题目保证正确的输出中没有超过整型范围的整数。
输入样例 1:
2/3 -4/2
输出样例 1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
输入样例 2:
5/3 0/6
输出样例 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
AC代码:
//#include<iostream>
//#include<cstring>
//#include<algorithm>
#include<cstdio>
#include<cmath>
using namespace std;
typedef long long LL;
struct Fraction{ //分数
LL up,down;
};
LL gcd(LL a,LL b){ //求最大公约数
return b==0?a:gcd(b,a%b);
}
Fraction reduction(Fraction f){ //分数化简
if(f.down<0){
f.up=-f.up;
f.down=-f.down;
}
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 f1,Fraction f2){ //分数相加
Fraction f;
f.up=f1.up*f2.down+f2.up*f1.down;
f.down=f1.down*f2.down;
return reduction(f);
}
Fraction minu(Fraction f1,Fraction f2){
Fraction f;
f.up=f1.up*f2.down-f2.up*f1.down;
f.down=f1.down*f2.down;
return reduction(f);
}
Fraction muti(Fraction f1,Fraction f2){
Fraction f;
f.up=f1.up*f2.up;
f.down=f1.down*f2.down;
return reduction(f);
}
Fraction divide(Fraction f1,Fraction f2){
Fraction f;
f.up=f1.up*f2.down;
f.down=f1.down*f2.up;
return reduction(f);
}
void showResult(Fraction f){
f=reduction(f);
if(f.up<0){
printf("(");
}
if(f.down==1){
printf("%lld",f.up);
}else if(abs(f.up)>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 f1,f2;
scanf("%lld/%lld %lld/%lld",&f1.up,&f1.down,&f2.up,&f2.down);
showResult(f1);printf(" + ");showResult(f2);printf(" = ");showResult(add(f1,f2));printf("\n");
showResult(f1);printf(" - ");showResult(f2);printf(" = ");showResult(minu(f1,f2));printf("\n");
showResult(f1);printf(" * ");showResult(f2);printf(" = ");showResult(muti(f1,f2));printf("\n");
showResult(f1);printf(" / ");showResult(f2);printf(" = ");
if(f2.up==0){
printf("Inf");
}else{
showResult(divide(f1,f2));
}
return 0;
}
疑惑:
为啥把命名空间去掉,测试点2和3就通过不了了???有哪位大佬帮忙解释一下
标签:f1,f2,有理数,四则运算,up,down,Fraction,printf,1034 来源: https://blog.csdn.net/zhoujie1233456/article/details/122760825