PAT1081 Rational Sum (20 分)

1. 除法和取余运算之前都要检查除数是否为0。

2. abs函数在cstdlib里,其它数学函数在cmath里。

3.辗转相除法求最大公约数,然后a/d*b求最小公倍数。

4.分数化简:为负时使分子问负分母为正(否则输出时负号位置会在分号后面);分子为0;最大公约数

5.分数输出:整数;假分数以带分数形式输出;真分数

#include <cstdio>
//#include <math.h>
#include <cstdlib>//solve "Call to 'abs' is ambiguous"
#define MAX 105
using namespace std;

typedef struct fraction{
    long up, down;
}Fraction;
Fraction fractions[MAX];

long gcd(long a, long b){
    if (b == 0) {
        return a;//
    }else{
        return gcd(b, a%b);//Thread 1: EXC_ARITHMETIC//除以(包括/和%)一个数之前要检查是否为0,仅当b不为0时才能作a%b
    }
}

Fraction simplify(Fraction a){
    if (a.down < 0) {
        a.down = - a.down;
        a.up = - a.up;
    }
    if (a.up == 0) {
        a.down = 1;
    }

    long d = gcd(abs(a.up), a.down);
    a.up /= d;
    a.down /= d;
    return a;
}

void displayFraction(Fraction a){
    a = simplify(a);
    if (a.down == 1) {
        printf("%ld", a.up);
    }else if (abs(a.up) > a.down){
        printf("%ld %ld/%ld", a.up/a.down, a.up%a.down, a.down);
    }else{
        printf("%ld/%ld", a.up, a.down);
    }
}

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 result;
}

int main(int argc, const char * argv[]) {
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        scanf("%ld/%ld", &fractions[i].up, &fractions[i].down);
    }
    
    Fraction sum = fractions[0];
    for (int i=1; i<N; i++) {
        sum = add(sum, fractions[i]);
    }
    
    displayFraction(sum);
    return 0;
}


//Sample Input 1:
//
//5
//2/5 4/15 1/30 -2/60 8/3
//Sample Output 1:
//
//3 1/3


//Sample Input 2:
//
//2
//4/3 2/3
//Sample Output 2:
//
//2


//Sample Input 3:
//
//3
//1/3 -1/6 1/8
//Sample Output 3:
//
//7/24

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值