欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

1034 有理数四则运算 (20分)

程序员文章站 2022-06-13 15:38:29
...

1034 有理数四则运算 (20分)

#include<stdio.h>
#include<algorithm>
using namespace std;
typedef long long ll;
struct fraction{
    ll up,down;
}temp1,temp2,a1,a2,a3,a4;
int gcd(ll a,ll b){
    if(b==0) return a;
    else return gcd(b,a%b);
}

fraction reduction(fraction result){
    if(result.down<0){
        result.up=-result.up;
        result.down=-result.down;
    }
    if(result.up==0)result.down=1;
    else{
        int d=gcd(abs(result.up),abs(result.down));
        result.up=result.up/d;
        result.down=result.down/d;
    }
    return result;
}
fraction add(fraction f1,fraction f2){
    fraction result;
    result.up=f1.up*f2.down+f1.down*f2.up;
    result.down=f1.down*f2.down;
    return reduction(result);
}
fraction minu(fraction f1,fraction f2){
    fraction result;
    result.up=f1.up*f2.down-f1.down*f2.up;
    result.down=f1.down*f2.down;
    return reduction(result);
}
fraction multi(fraction f1,fraction f2){
    fraction result;
    result.up=f1.up*f2.up;
    result.down=f1.down*f2.down;
    return reduction(result);
}
fraction divide(fraction f1,fraction f2){
    fraction result;
    result.up=f1.up*f2.down;
    result.down=f1.down*f2.up;
    return reduction(result);
}
void showresult(fraction r){
    r=reduction(r);
    if(r.down==0) printf("Inf");
    if(r.down==1) {
        if(r.up<0)printf("(%lld)",r.up);
        else printf("%lld",r.up);
    }
    else if(abs(r.up)>r.down){
        if(r.up<0)printf("(%lld %lld/%lld)",r.up/r.down,abs(r.up)%r.down,r.down);
        else printf("%lld %lld/%lld",r.up/r.down,abs(r.up)%r.down,r.down);
    }else {
        if(r.up<0)printf("(%lld/%lld)",r.up,r.down);
        else printf("%lld/%lld",r.up,r.down);
    }
}

int main(){
    scanf("%lld/%lld %lld/%lld",&temp1.up,&temp1.down,&temp2.up,&temp2.down);
    temp1=reduction(temp1);
    temp2=reduction(temp2);

    a1=add(temp1,temp2);
    a2=minu(temp1,temp2);
    a3=multi(temp1,temp2);
    a4=divide(temp1,temp2);
    showresult(temp1);
    printf(" + ");
    showresult(temp2);
    printf(" = ");
    showresult(a1);
printf("\n");
    showresult(temp1);
    printf(" - ");
    showresult(temp2);
    printf(" = ");
    showresult(a2);
printf("\n");
    showresult(temp1);
    printf(" * ");
    showresult(temp2);
    printf(" = ");
    showresult(a3);
printf("\n");
    showresult(temp1);
    printf(" / ");
    showresult(temp2);
    printf(" = ");
    if(temp2.up==0)
        printf("Inf");
    else showresult(a4);
printf("\n");
}

第一次,参考算法笔记完成,40min