题目链接
没说范围,最好用long long 测试点也确实超过了int;
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
#pragma warning(disable:4996);
#include <iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<string>
#include<stack>
#include<math.h>
#include<vector>
using namespace std;
long long gcd(long long a, long long b)
{
if (b == 0) return a;
else return gcd(b, a % b);
}//求最大公约数;
void printnum(long long a, long long b)//a为分子,b为分母;对输出格式进行处理;
{
long long temp, c, d;
if (b < 0) { //分母<0则分子分母变号,保持分母为正
b = -b; a = -a;
}
else if (b == 0) {//分母为0,为inf
printf("Inf");
return;
}
if (a < 0) printf("(");//有负数时,要输出();
else if (a == 0) {
printf("0");
return;
}
if (a % b == 0)//a是b的倍数,直接输出一个整数;
printf("%lld", a / b);
else {
temp = gcd(a, b);
if (temp < 0)temp = -temp;//最大正公约数,不然有负数时,处理会很麻烦;
a = a / temp;b = b / temp;
c = a > 0 ? a : -a;//分子的绝对值;用来做输出的判断,以及处理;
if (c < b) printf("%lld/%lld", a, b); //分子绝对值小于分母 输出一个分数
else if (c > b && a < 0)//分子绝对值大于分母 分母小于0
printf("%lld %lld/%lld", a / b, -(a - (a / b) * b), b);
//利用a/b来取到整数,用 -(a - (a / b) * b),取分子;
else if (c > b && a > 0)//都为正数时
printf("%lld %lld/%lld", a / b, a - (a / b) * b, b);
}
if (a < 0)printf(")");//控制括号
}
int main() {
long long a, b, c, d;
scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d);
printnum(a, b); printf(" + "); printnum(c, d); printf(" = "); printnum(a * d + b * c, b * d); printf("\n");
printnum(a, b); printf(" - "); printnum(c, d); printf(" = "); printnum(a * d - b * c, b * d); printf("\n");
printnum(a, b); printf(" * "); printnum(c, d); printf(" = "); printnum(a * c, b * d); printf("\n");
printnum(a, b); printf(" / "); printnum(c, d); printf(" = "); printnum(a * d, b * c); printf("\n");
return 0;
//输出结果的inf交由正常的编译计算产生;
}