clipboard.png
分数计算,之前做过相关的总结,这里不再赘述
代码如下:

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string>
using namespace std;
const int maxn=110;
typedef long long LL;
struct node{
    LL up;
    LL down;
};

LL str2num(string s){
    LL sum=0;
    for(int i=0;i<s.size();i++){
        sum=sum*10+(s[i]-'0');
    }
    return sum;
}

int gcd(int a,int b){
    if(b==0)
        return a;
    return gcd(b,a%b);
}

node reflesh(node a){
    if(a.down<0){
        a.up=-a.up;
        a.down=-a.down;
    }
    if(a.up==0){
        a.down=1;
    }else{
        int d;
        if(abs(a.up)>abs(a.down)){
            d=gcd(abs(a.up),abs(a.down));
        }else{
            d=gcd(abs(a.down),abs(a.up));
        }
        a.down/=d;
        a.up/=d;
    }
    return a;
}

node add(node a,node b){
    node result;
    result.down=a.down*b.down;
    result.up=a.up*b.down+a.down*b.up;
    return reflesh(result);
}

void output(node a){
    //reflesh(a);
    if(a.down==1)
        printf("%lld\n",a.up);
    else if(abs(a.up)>a.down){
        printf("%lld %lld/%lld\n",a.up/a.down,abs(a.up)%a.down,a.down);
    }else{
        printf("%lld/%lld\n",a.up,a.down);
    }
}

int main(){
    int N;
    node f,s;
    s.down=1;
    s.up=0;
    scanf("%d",&N);
    for(int i=0;i<N;i++){
        scanf("%lld/%lld",&f.up,&f.down);
        s=add(s,f);
    }
    output(s);
    system("pause");
    return 0;
}

宋霖轩
16 声望4 粉丝

克哈的霓虹都为我闪烁