【PAT】A1081 Rational Sum (分数加法)

【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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值