1081 Rational Sum (20分)

6 篇文章 0 订阅

在这里插入图片描述
在这里插入图片描述

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
long long gcd(long long a, long long b) {
	return b == 0 ? a : gcd(b, a % b);
}
struct fraction {
	long long up, down;
	fraction(long long u, long long d) {
		up = u;
		down = d;
	}
};
//返回最简的分数
fraction reduce(fraction f) {
	long long c = gcd(f.up, f.down);
	f.up /= c;
	f.down /= c;
	return f;
}
fraction add(fraction a, fraction b) {
	fraction res(0, 1);
	long long common = gcd(a.down, b.down);
	res.up = a.up * (b.down / common) + b.up * (a.down / common);
	res.down = a.down / common * b.down;
	return res;
}
string getString(fraction f) {
	if (f.up == 0) {
		return "0";
	}
	string res;
	bool negative = false;
	if (f.up < 0) {
		f.up = -f.up;
		negative = true;
	}
	long long integer = f.up / f.down;
	f.up %= f.down;
	if (integer != 0) {
		res += to_string(integer);
		if (f.up != 0) {
			res += " ";
		}
	}
	if (f.up != 0) {
		res += to_string(f.up) + "/" + to_string(f.down);
	}
	if (negative) {
		res = "-" + res;
	}
	return res;
}
int main() {
	int numInput;
	cin >> numInput;
	fraction res(0, 1);
	for (int i = 0; i < numInput; i++) {
		fraction temp(0, 1);
		scanf("%lld/%lld", &temp.up, &temp.down);
		temp = reduce(temp);
		res = add(res, temp);
		res = reduce(res);
	}
	string s = getString(res);
	cout << s;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值