A1081 Rational Sum [分数计算]

在这里插入图片描述
题意:分数的计算
注意

  1. 每步都要化简(求最大公约数),防止溢出
  2. 真分数假分数要判断输出
#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;
};
fraction simplify(fraction result)
{
    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);
}
void showresult(fraction r)
{
	if (r.down == 1)
		printf("%lld
", 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);
	}
}
int main()
{
	int n;
	cin >> n;
	fraction sum, temp;
	sum.up = 0, sum.down = 1;
	for (int i = 0; i < n; i++)
	{
		scanf("%lld/%lld", &temp.up, &temp.down);
		sum = add(sum, temp);
	}
	showresult(sum);
	return 0;
}
原文地址:https://www.cnblogs.com/Hsiung123/p/13812048.html