PAT甲级(1)Rational Sum

题目描述
Given N rational numbers in the form “numerator/denominator”, you are supposed to calculate their sum.

输入描述:
Each input file contains one test case. Each case starts with a positive integer N (<=100), followed in the next line N rational numbers “a1/b1 a2/b2 …” where all the numerators and denominators are in the range of “long int”. If there is a negative number, then the sign must appear in front of the numerator.

输出描述:
For each test case, output the sum in the simplest form “integer numerator/denominator” where “integer” is the integer part of the sum, “numerator” < “denominator”, and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0.

输入例子:
5
2/5 4/15 1/30 -2/60 8/3

输出例子:
3 1/3

# include<iostream>
#include <stdio.h>
#include<algorithm>
using namespace std;
struct fraction {
    int up, down;
    fraction() { up = 0, down = 1; }
};
int gcd(int a, int b)
{
    a = abs(a), b = abs(b);
    if (a < b)swap(a, b);
    return b == 0 ? a : gcd(b, a%b);
}
fraction reduction(fraction x)
{
    if (x.down < 0)x.up = -x.up, x.down = -x.down;  //如果分母为负数则负号转移到分子上
    if (x.down == 0)x.up = 1;
    else
    {
        int d = gcd(x.up, x.down);
        x.up /= d;
        x.down /= d;
    }
    return x;
}
fraction add(fraction x, fraction y)
{
    fraction result;
    result.up = x.up*y.down + y.up*x.down;
    result.down = x.down*y.down;
    result = reduction(result);
    return result;
}
void showresult(fraction x)
{
    if (x.down == 1) printf("%d", x.up);
    else if (abs(x.up) < x.down) printf("%d/%d", x.up, x.down);
    else printf("%d %d/%d", x.up / x.down, abs(x.up) % x.down, x.down);
}
int main()
{
    int n;
    scanf("%d", &n);
    fraction result;
    while (n--)
    {
        fraction temp;
        scanf("%d/%d", &temp.up, &temp.down);
        result = add(result, temp);
    }
    showresult(result);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

coder鹏鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值