疑问
暂无
代码
//为什么是rational呢,因为分数都是有理数呀
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
struct Fraction{
ll up;
ll down;
};
Fraction x;
Fraction y;
long long gcd(ll a,ll b){
if(b == 0){
return a;
}else{
return gcd(b,a%b);
}
}
void showResult(Fraction res){
//1.如果是负数
if(res.up < 0){
printf("(");
//如果是整数
if(res.down == 1){
printf("%lld",res.up);
}else if(abs(res.up) > res.down){
//如果是假分数
printf("%lld ",res.up / res.down);
printf("%lld/%lld",abs(res.up) % res.down,res.down);
}else{
//是真分数
printf("%lld/%lld",res.up,res.down);
}
printf(")");
}else{
//如果是整数
if(res.down == 1){
printf("%lld",res.up);
}else if(abs(res.up) > res.down){
//如果是假分数
printf("%lld ",res.up / res.down);
printf("%lld/%lld",abs(res.up) % res.down,res.down);
}else{
//是真分数
printf("%lld/%lld",res.up,res.down);
}
}
}
Fraction reduction(Fraction f){
//如果分母是负数
if(f.down < 0){
f.up = -f.up;
f.down = -f.down;
}
//如果是0
if(f.up == 0){
f.down = 1;
}else{
long long num = gcd(abs(f.up),abs(f.down));
f.up = f.up / num;
f.down = f.down / num;
}
return f;
}
//加法
void add(Fraction x,Fraction y){
Fraction res;
showResult(x);
printf(" + ");
showResult(y);
printf(" = ");
res.up = x.up * y.down + y.up * x.down;
res.down = x.down * y.down;
res = reduction(res);
showResult(res);
}
//减法
void sub(Fraction x,Fraction y){
Fraction res;
showResult(x);
printf(" - ");
showResult(y);
printf(" = ");
res.up = x.up * y.down - y.up * x.down;
res.down = x.down * y.down;
res = reduction(res);
showResult(res);
}
//乘法
void multi(Fraction x,Fraction y){
Fraction res;
showResult(x);
printf(" * ");
showResult(y);
printf(" = ");
res.up = x.up * y.up;
res.down = x.down * y.down;
res = reduction(res);
showResult(res);
}
//除法
void divide(Fraction x,Fraction y){
Fraction res;
showResult(x);
printf(" / ");
showResult(y);
printf(" = ");
if(y.up == 0){
printf("Inf");
}else{
res.up = x.up * y.down;
res.down = x.down * y.up;
res = reduction(res);
showResult(res);
}
}
int main(){
scanf("%lld/%lld %lld/%lld",&x.up,&x.down,&y.up,&y.down);
x = reduction(x);
y = reduction(y);
add(x,y);
printf("\n");
sub(x,y);
printf("\n");
multi(x,y);
printf("\n");
//注意除法要特判
divide(x,y);
return 0;
}
反思
- 我的代码好丑.jpg。
来源:CSDN
作者:yc_cy1999
链接:https://blog.csdn.net/yc_cy1999/article/details/104563455