A1088 Rational Arithmetic [分数四则运算]

在这里插入图片描述

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b)
{
	if (b == 0)
		return a;
	else
		return gcd(b, a % b);
}
struct fraction
{
	ll up, down;
}f1,f2;
fraction simplify(fraction result)
{
	if (result.down < 0)
	{
		result.up = -result.up;
		result.down = -result.down;
	}
	int d = gcd(abs(result.up), abs(result.down));
	result.up /= d;
	result.down /= d;
	return result;
}
fraction add(fraction a, fraction b)
{
	fraction result;
	result.up = a.up * b.down + b.up * a.down;
	result.down = a.down * b.down;
	return simplify(result);
}
fraction Minus(fraction a, fraction b)
{
	fraction result;
	result.up = a.up * b.down - b.up * a.down;
	result.down = a.down * b.down;
	return simplify(result);
}
fraction mul(fraction a, fraction b)
{
	fraction result;
	result.up = a.up * b.up;
	result.down = a.down * b.down;
	return simplify(result);
}
fraction divide(fraction a, fraction b)
{
	fraction result;
	result.up = a.up * b.down;
	result.down = a.down * b.up;
	return simplify(result);
}
void showresult(fraction r)
{
	r = simplify(r);
	if (r.up < 0)
		cout << "(";
	if (r.down == 1)
		cout << r.up;
	else if (abs(r.up) > abs(r.down))
	{
		printf("%lld %lld/%lld", r.up / r.down, abs(r.up) % r.down, r.down);
	}
	else
	{
		printf("%lld/%lld", r.up, r.down);
	}
	if (r.up < 0)
		cout << ")";
}
int main()
{
	scanf("%lld/%lld %lld/%lld", &f1.up, &f1.down, &f2.up, &f2.down);
	showresult(f1);
	printf(" + ");
	showresult(f2);
	cout << " = ";
	showresult(add(f1, f2));
	cout << endl;
	showresult(f1);
	printf(" - ");
	showresult(f2);
	cout << " = ";
	showresult(Minus(f1, f2));
	cout << endl;
	showresult(f1);
	printf(" * ");
	showresult(f2);
	cout << " = ";
	showresult(mul(f1, f2));
	cout << endl;
	showresult(f1);
	printf(" / ");
	showresult(f2);
	cout << " = ";
	if (f2.up == 0)
		cout << "Inf";
	else
		showresult(divide(f1, f2));
	return 0;
}
原文地址:https://www.cnblogs.com/Hsiung123/p/13812047.html