甲级| 1081.Rational Sum

题目描述

iven 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
#include
using namespace std;
long long gcd(long long a,long long  b){
    if(b==0) return a;
    return gcd(b,a%b);
}

struct Fraction{
    long long up;
    long long down;
}t;

Fraction reduction(Fraction fra){
    if(fra.up<0){
        fra.up=-fra.up;
        fra.down=-fra.down;
    }
    if(fra.up==0){
        fra.down=1;
    }
    else{
        long long d=gcd(abs(fra.up),abs(fra.down));
        fra.up=fra.up/d;
        fra.down=fra.down/d;
    }
    return fra;
}

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 reduction(result);
}

void showf(Fraction f){
    reduction(f);
    if(f.down==1){
        printf("%lld",f.up);
    }
    else if(abs(f.up)>abs(f.down)){
        printf("%lld %lld/%lld",f.up/f.down,abs(f.up)%f.down,f.down);
    }
    else{
        printf("%lld/%lld",f.up,f.down);
    }
    
}

int main(){
    int n;
    scanf("%d",&n);
    Fraction sum; 
    sum.up=0;
    sum.down=1;
    for(int i=0;i

你可能感兴趣的:(甲级| 1081.Rational Sum)