本题要求编写程序,计算 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
代码长度限制
16 KB
时间限制
200 ms
内存限制
64 MB
#include <iostream>
#include <cmath>
using namespace std;
typedef long long ll;
void easy(ll,ll); //化简分子,分母
ll gcd(ll, ll); //最大公约数
int main()
{
ll a1, b1, a2, b2;
cin >> a1, cin.get(), cin >> b1, cin.get(), cin >> a2, cin.get(), cin >> b2, cin.get();
easy(a1, b1); cout << " + "; easy(a2, b2); cout << " = "; easy(a1 * b2 + a2 * b1, b1 * b2); cout << endl;
easy(a1, b1); cout << " - "; easy(a2, b2); cout << " = "; easy(a1 * b2 - a2 * b1, b1 * b2); cout << endl;
easy(a1, b1); cout << " * "; easy(a2, b2); cout << " = "; easy(a1 * a2, b1 * b2); cout << endl;
easy(a1, b1); cout << " / "; easy(a2, b2); cout << " = "; easy(a1 * b2, b1 * a2); cout << endl;
return 0;
}
void easy(ll up, ll down)
{
int isfu = 0;
if (down == 0)
{
cout << "Inf";
return;
}
if (up == 0)
{
cout << "0";
return;
}
if ((up > 0 && down < 0) || (up < 0 && down>0))
isfu = 1;
if (isfu)
cout << "(-";
up = abs(up);
down = abs(down);
int front = up / down;
if (front)
{
cout << front;
up -= front * down;
}
int tmp = gcd(up, down);
up /= tmp;
down /= tmp;
if (up)
{
if (front)
cout << ' ';
cout << up << '/' << down;
}
if (isfu)
cout << ')';
}
ll gcd(ll n1, ll n2)
{
if (n1 % n2)
return gcd(n2, n1 % n2);
return n2;
}