1034. 有理数四则运算(20)
时间限制
200 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue
本题要求编写程序,计算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
vvvv 还差两个小梗 找不到点啊啊啊啊,,,
#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "string"
#include "ctype.h"
#include "vector"
#include "algorithm"
#include "map"
#include "math.h"
using namespace std;
char sign[4] = { '+','-','*','/' };
int CommonDivisor(long long a, long long b) {
int r;
if (a<b) {
r = a;
a = b;
b = r;
}
while (b != 0)
{
r = a%b;
a = b;
b = r;
}
return a;
}
int printNum(long long a, long long b) {
int f = a / b;
int r = a%b;
if (f == 0) //整数部分为0
{
if (r == 0) //完全等于0
{
cout << "0";
}
else {
int ccm = CommonDivisor(r, b);
if (a*b<0) // 负分数
{
cout << "(-" << abs(r / ccm) << "/" << abs(b / ccm) << ")";
}
else {
cout << abs(r / ccm) << "/" << abs(b / ccm);
}
}
}
else {
if (f<0)
{
cout << "(";
}
cout << f;
if (r != 0)
{
//要求公约数
int ccm = CommonDivisor(r, b);
cout << " " << abs(r / ccm) << "/" << abs(b / ccm);
}
if (f<0)
{
cout << ")";
}
}
return 0;
}
void printForm(long long a, long long b, long long c, long long d, long long index) {
printNum(a, b);
cout << " " << sign[index] << " ";
printNum(c, d);
cout << " = ";
if (index == 0)
{
printNum(a*d + c*b, b*d);
}
else if (index == 1) {
printNum(a*d - c*b, b*d);
}
else if (index == 2) {
printNum(a*c, b*d);
}
else {
if (b*c == 0) {
cout << "Inf";
}
else {
printNum(a*d, b*c);
}
}
cout << endl;
}
int main() {
long long a, b, c, d;
scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d);
for (int i = 0; i<4; i++)
{
printForm(a, b, c, d, i);
}
}
说是整数范围内,其实变量范围要是long long