【PAT】A1081 Rational Sum (分数加法)
@(PAT)
链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805386161274880
思路:
1. 题目意思很简单,分数加法,但是要注意细节。
2. 最大公约数的写法,辗转相除法。
3. 化简时,负数的处理,分母是负数的话,就让分子和分母都置为相反数;分子为0,同时记得置分母为1。
4. 最后输出的处理,要区分整数、真分数、假分数。
My AC code:
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
typedef long long ll;
using namespace std;
struct fenshu
{
ll fenzi;
ll fenmu;
};
ll gcd(ll a, ll b) {
// insure a> b
if (a < b) {
int temp = b;
b = a;
a = temp;
}
int r, t;
while (b != 0) {
r = a% b;
a = b;
b = r;
}
return a;
}
fenshu reduce(fenshu a) {
fenshu res;
if (a.fenmu < 0) {
a.fenzi = 0 - a.fenzi;
a.fenmu = 0 - a.fenmu;
}
if (a.fenzi == 0) {
a.fenmu = 1;
}
else {
ll g = gcd(a.fenzi, a.fenmu);
a.fenzi = a.fenzi / g;
a.fenmu = a.fenmu / g;
}
return a;
}
fenshu mAdd(fenshu a, fenshu b) {
fenshu res;
res.fenzi = a.fenzi* b.fenmu + a.fenmu* b.fenzi;
res.fenmu = a.fenmu* b.fenmu;
return reduce(res);
}
int main()
{
int n;
scanf("%d", &n);
fenshu ans;
fenshu temp;
ans.fenmu = 1;
ans.fenzi = 0;
for (int i = 0; i < n; i++) {
scanf("%lld/%lld", &temp.fenzi, &temp.fenmu);
ans= mAdd(ans, temp);
}
ans= reduce(ans);
if (ans.fenzi == 0) {
printf("0");
}
else if (ans.fenmu== 1) {
printf("%lld", ans.fenzi);
}
else if (abs(ans.fenzi) - ans.fenmu > 0) {
printf("%lld %lld/%lld", ans.fenzi/ans.fenmu, abs(ans.fenzi)%ans.fenmu, ans.fenmu);
}
else {
printf("%lld/%lld", ans.fenzi, ans.fenmu);
}
}
本文介绍PAT A1081 RationalSum题目,重点讲解分数加法的实现方法,包括最大公约数计算、分数化简及输出处理等关键步骤。
1495

被折叠的 条评论
为什么被折叠?



