// B1034 有理数四则运算 (20分).cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
learn && wrong:
1、公约数要绝对值
2、化简是if,if_else
3、输出是if_else_else if
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b) {
if (b == 0) {
return a;
}
else {
return gcd(b, a % b);
}
}
struct Fraction {
ll up;
ll down;
}a,b;
Fraction reduction(Fraction result) { //化简
if (result.down < 0) {
result.up = -result.up;
result.down = -result.down;
}
if (result.up == 0) {
result.down = 1;
}
else {
ll d = gcd(abs(result.up), abs(result.down));
result.up = result.up / d;
result.down = result.down / d;
}
return result;
}
Fraction add(Fraction a, Fraction b) {
Fraction result;
result.up = a.up * b.down + a.down * b.up;
result.down = a.down * b.down;
return reduction(result);
}
Fraction sub(Fraction a, Fraction b) {
Fraction result;
result.up = a.up * b.down - a.down * b.up;
result.down = a.down * b.down;
return reduction(result);
}
Fraction plus1(Fraction a, Fraction b) {
Fraction result;
result.up = a.up * b.up;
result.down = a.down * b.down;
return reduction(result);
}
Fraction division(Fraction a, Fraction b) {
Fraction result;
result.up = a.up * b.down;
result.down = a.down * b.up;
return reduction(result);
}
void show(Fraction r) {
//如果是负数,如果是0,如果是假分数
r = reduction(r);
if (r.up < 0)printf("(");
if (r.down == 1) printf("%lld", r.up);
else if (abs(r.up) > r.down) {
printf("%lld %lld/%lld", r.up / r.down, abs(r.up) % r.down, r.down);
}
else {
printf("%lld/%lld", r.up, r.down);
}
if (r.up < 0) printf(")");
}
int main()
{
scanf("%lld/%lld %lld/%lld", &a.up, &a.down, &b.up, &b.down);
show(a);
printf(" + ");
show(b);
printf(" = ");
show(add(a, b));
printf("\n");
show(a);
printf(" - ");
show(b);
printf(" = ");
show(sub(a, b));
printf("\n");
show(a);
printf(" * ");
show(b);
printf(" = ");
show(plus1(a, b));
printf("\n");
show(a);
printf(" / ");
show(b);
printf(" = ");
if (b.up == 0) printf("Inf");
else show(division(a, b));
printf("\n");
return 0;
}
网友评论