分数表示
分数化简
分数四则
分数输出
代码
#include <iostream>
using namespace std;
/*---- 分数的表示 ----*/
struct Fraction {
int up,down; //乘除 可能溢出时使用long long
};
/*----- 分数的化简 -----*/
int gcd(int a,int b) {
if(b==0)return a;
return gcd(b,a%b);
}
Fraction reduction(Fraction result) {
// 1 如果分母小于0,分子分母同时取相反数
if(result.down<0) {
result.up=-result.up;
result.down=-result.down;
}
// 2 如果分子为0,分母置为1
if(result.up==0)result.down=1;
else {
// 3 如果分子分母有最大公约数,同除最大公约数
int gc = gcd(abs(result.up),abs(result.down));
result.up/=gc;
result.down/=gc;
}
return result;
}
/*----- 分数的四则运算 -----*/
Fraction add(Fraction a, Fraction b) {
Fraction c;
c.up=a.up*b.down+a.down*b.up;
c.down=a.down*b.down;
return reduction(c);
}
Fraction sub(Fraction a, Fraction b) {
Fraction c;
c.up=a.up*b.down-b.up*a.down;
c.down=a.down*b.down;
return reduction(c);
}
Fraction multi(Fraction a, Fraction b) {
Fraction c;
c.up=a.up*b.up;
c.down=a.down*b.down;
return reduction(c);
}
Fraction divid(Fraction a, Fraction b) {
Fraction c;
c.up=a.up*b.down;
c.down=a.down*b.up;
return reduction(c);
}
/*----- 分数的输出 -----*/
void showResult(Fraction r) {
r = reduction(r);
// 若分母为1,直接输出分子
if(r.down==1)printf("%d",r.up);
// 若为假分数,输出带分数形式
else if(abs(r.up)>r.down)printf("%d %d/%d",r.up/r.down, abs(r.up)%r.down, r.down);
// 真分数
else printf("%d/%d",r.up,r.down);
}
int main(int argc,char * argv[]) {
int a,b,d,e;
char c;
scanf("%d%d %c %d%d",&a,&b,&c,&d,&e);
// 如果分母为0,直接输出错误
if(b==0||e==0)printf("error");
Fraction f;
if(c=='+')f = add({a,b}, {d,e});
if(c=='-')f = sub({a,b}, {d,e});
if(c=='*')f = multi({a,b}, {d,e});
if(c=='/')f = divid({a,b}, {d,e});
// printf("%d/%d",f.up,f.down);
showResult(f);
return 0;
}