分数的加减乘除,输出

#include<bits/stdc++.h>
using namespace std;

struct fraction{
    int up;
    int down;
    fraction(){}
    fraction(int a,int b):up(a),down(b){
    }
    friend ostream & operator<<(ostream &out,const fraction & t){
        out<<t.up<<"/"<<t.down;
        return out;
    }
    void show(fraction a){
        a=reduction(a);
        if(a.down==1){
            cout<<a.up<<endl;
        }
        else if(abs(a.up)>abs(a.down)){
            cout<<a.up/a.down<<abs(a.up)%a.down<<a.down<<endl;
        }
        else{
            cout<<a<<endl;
        }
    }
}f;

int gcd(int a,int b){
    return b?gcd(b,a%b):a;
}

fraction reduction(fraction a){
    if(a.down<0){
        a.up=-a.up;
        a.down=-a.down;
    }
    if(a.up==0){
        a.down=1;
    }
    else{
        int b=gcd(abs(a.up),abs(a.down));
        a.up/=b;
        a.down/=b;
    }
    return a;
}

fraction add(fraction a,fraction b){
    a.up=a.up*b.down+a.down*b.up;
    a.down=a.down*b.down;
    return reduction(a);
}

fraction sub(fraction a,fraction b){
    a.up=a.up*b.down-a.down*b.up;
    a.down=a.down*b.down;
    return reduction(a);
}

fraction mul(fraction a,fraction b){
    a.up=a.up*b.up;
    a.down=a.down*b.down;
    return reduction(a);
}

fraction div(fraction a,fraction b){
    a.up=a.up*b.down;
    a.down=a.down*b.up;
    return reduction(a);
}

int main(){
    while(cin>>f.up>>f.down){
        cout<<reduction(f)<<endl;
    }
    return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
自来熟的放鸽子能手面...:这个不一定,找hr跟进一下
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务