1088 Rational Arithmetic (20分)

这个题目关键是写一个化简函数,测试点3和4考察的是 对负数的处理
测试点4不能用 a*b<0判断 负数,因为会溢出。
测试点3就是分母为负数的情况。

附本人AC代码:

#include<iostream>
#include<string>
#include<math.h>
using namespace std;
long long gcd(long long A, long long B) {
	return B == 0 ? A : gcd(B,A%B);
}
string simply(long long a, long long b) {
	bool flag = false;
	string s;
	if ((long long)a*(long long)b<(long long)0) {
		a = abs(a);
		b = abs(b);
		flag = true;
		s += "(-";
	}
	if (a == 0)return "0";
	long long t = gcd(a, b);
	a /= t;
	b /= t;
	t = a / b;
	if (t > 0) {
		s += to_string(t);
		a -= t * b;
	}
	if (a > 0) {
		if (t>0)s += " ";
		s +=to_string(a) + "/" + to_string(b);
	}
	if (flag)s += ")";
	return s;
}
int main() {
	long long f1, f2, m1, m2;
	scanf("%lld/%lld %lld/%lld", &f1, &m1, &f2, &m2);
	cout << simply(f1, m1) + " + " + simply(f2, m2) + " = " + simply(f1*m2 + f2 * m1, m1*m2) << endl;
	cout << simply(f1, m1) + " - " + simply(f2, m2) + " = " + simply(f1*m2 - f2 * m1, m1*m2) << endl;
	cout << simply(f1, m1) + " * " + simply(f2, m2) + " = " + simply(f1*f2, m1*m2) << endl;
	if (abs(f2) == 0)cout << simply(f1, m1) + " / " + simply(f2, m2) + " = Inf";
	else cout << simply(f1, m1) + " / " + simply(f2, m2) + " = "+simply(f1*m2, f2*m1);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值