本题要求编写程序,计算 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
#include <stdio.h>
#include <iostream>
using namespace std;
//求最大公约数
long getnum(long a, long b)
{
long r = a % b;
while(r != 0)
{
a = b;
b = r;
r = a % b;
}
return b;
}
//化简
void simple(long a, long b)
{
long flag = 1;
if(b == 0)
{
cout << "Inf" <<endl;
return;
}
if(a < 0)
{
a = -a;
flag = -flag;
}
if(b < 0)
{
b = -b;
flag = -flag;
}
if(flag < 0)
cout << "(-";
long r = getnum(a, b);
a /= r;
b /= r;
if(b == 1) cout << a;
else if(a < b) cout << a << "/" <<b;
else if(a > b) cout << a/b << " " << a % b << "/" << b;
if(flag < 0) cout << ")";
return;
}
int main()
{
long a1, b1, a2, b2;
scanf("%ld/%ld %ld/%ld", &a1, &b1, &a2, &b2);
simple(a1, b1);
cout << " + ";
simple(a2, b2);
cout << " = ";
simple(a1 * b2 + a2 * b1, b1 * b2);
cout << endl;
simple(a1, b1);
cout << " - ";
simple(a2, b2);
cout << " = ";
simple(a1 * b2 - a2 * b1, b1 * b2);
cout << endl;
simple(a1, b1);
cout << " * ";
simple(a2, b2);
cout << " = ";
simple(a1 * a2, b1 * b2);
cout << endl;
simple(a1, b1);
cout << " / ";;
simple(a2, b2);
cout << " = ";;
simple(a1 * b2, b1 * a2);
}
来源:CSDN
作者:rockkyy
链接:https://blog.csdn.net/lx18303916/article/details/104066419