1034 有理数四则运算

题目链接
没说范围,最好用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交由正常的编译计算产生;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值