本题要求编写程序,计算 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
代码:
// ConsoleApplicationB 1034.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<cstdio>
#include<cmath>
using namespace std;
typedef long long ll;
struct Fraction
{
ll up;
ll down;
};
ll gcd(ll a, ll b)
{
if (b == 0)
{
return a;
}
else
{
return gcd(b,a % b);
}
}
Fraction reduction(Fraction f1)
{
ll g;
if (f1.down < 0)
{
f1.up = -f1.up;
f1.down = -f1.down;
}
if (f1.up == 0)f1.down = 1;
else {
g = gcd(abs(f1.up), abs(f1.down));
f1.up /= g;
f1.down /= g;
}
return f1;
}
void showResult(Fraction f)
{
if (f.up < 0)cout << "(";
if (f.down == 1)
{
cout << f.up;
}
else if(abs(f.up)<f.down)
{
printf("%lld/%lld", f.up, f.down);
}
else
{
printf("%lld %lld/%lld", f.up/f.down,abs(f.up)-(abs(f.up / f.down))*f.down ,f.down);
}
if (f.up < 0)cout << ")";
}
int lcm(ll a, ll b)
{
return a * b * gcd(a, b);
}
Fraction add(Fraction f1, Fraction f2)
{
Fraction f;
ll l;
l = lcm(f1.down, f2.down);
f1.up *= (l / f1.down);
f2.up *= (l / f2.down);
f.up = f1.up + f2.up;
f.down = l;
return f;
}
Fraction minu(Fraction f1, Fraction f2)
{
Fraction f;
ll l;
l = lcm(f1.down, f2.down);
f1.up *= (l / f1.down);
f2.up *= (l / f2.down);
f.up = f1.up - f2.up;
f.down = l;
return f;
}
Fraction multi(Fraction f1, Fraction f2)
{
Fraction f;
f.up = f1.up * f2.up;
f.down = f1.down*f2.down;
return f;
}
Fraction devide(Fraction f1, Fraction f2)
{
Fraction f;
f.up = f1.up * f2.down;
f.down = f1.down * f2.up;
return f;
}
int main()
{
Fraction f1, f2;
scanf("%lld/%lld %lld/%lld", &f1.up, &f1.down, &f2.up, &f2.down);
//加法
showResult(reduction(f1));
cout << " + ";
showResult(reduction(f2));
cout << " = ";
showResult(reduction(add(f1, f2)));
cout << endl;
//减法
showResult(reduction(f1));
cout << " - ";
showResult(reduction(f2));
cout << " = ";
showResult(reduction(minu(f1, f2)));
cout << endl;
//乘法
showResult(reduction(f1));
cout << " * ";
showResult(reduction(f2));
cout << " = ";
showResult(reduction(multi(f1, f2)));
cout << endl;
//除法
showResult(reduction(f1));
cout << " / ";
showResult(reduction(f2));
cout << " = ";
if (devide(f1, f2).down == 0)
{
cout << "Inf";
}
else {
showResult(reduction(devide(f1, f2)));
}
return 0;
}
/*
-3/2 4/7
*/
- 使用结构体存储分数;
- 求最大公约数和最小公倍数时取绝对值;
- 对于分子为0的情况,将分母置为1,这和其他化简后为整数的分数处理方法相同;
- 除法计算中,要注意计算结果的分母为0的情况,打印出Inf。