PAT (Basic Level) 1034 有理数四则运算

题意

给定两个分数,计算加减乘除,核心在于转化为要求的格式输出。

思路

gcd化简,提取整数部分,注意各种形式的输出要求,注意corner point。

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
	int64_t a1, a2, b1, b2;
	scanf("%lld/%lld %lld/%lld",&a1, &b1, &a2, &b2);
	auto solve = [](int64_t a, int64_t b) -> string {
		if (b == 0) return "Inf";
		if (a == 0) return "0";
		if (b < 0) {b *= -1; a *= -1;}
		int64_t gcd = __gcd(abs(a), b);
		a /= gcd;
		b /= gcd;
		int64_t z = abs(a) / b, fz = abs(a) % b;
		string res = "";
		if (a < 0) res += "(-";
		if (z != 0) res += to_string(z);
		if (z != 0 && fz != 0) res += " ";
		if (fz != 0) {
			res += to_string(fz);
			res += "/";
			res += to_string(b);
		}
		if (a < 0) res += ")";
		return res;
	};
	printf("%s + %s = %s\n", solve(a1, b1).c_str(), solve(a2, b2).c_str(), solve(a1 * b2 + a2 * b1, b1 * b2).c_str());
	printf("%s - %s = %s\n", solve(a1, b1).c_str(), solve(a2, b2).c_str(), solve(a1 * b2 - a2 * b1, b1 * b2).c_str());
	printf("%s * %s = %s\n", solve(a1, b1).c_str(), solve(a2, b2).c_str(), solve(a1 * a2, b1 * b2).c_str());
	printf("%s / %s = %s\n", solve(a1, b1).c_str(), solve(a2, b2).c_str(), solve(a1 * b2, a2 * b1).c_str());
	return 0;
} 

HINT

不定时更新更多题解,Basic Level 全部AC代码,详见 link ! ! !

发布了50 篇原创文章 · 获赞 15 · 访问量 2685

猜你喜欢

转载自blog.csdn.net/abcdefbrhdb/article/details/104592623
今日推荐