您好,欢迎来到微智科技网。
搜索
您的当前位置:首页PAT A 1088 Rational Arithmetic

PAT A 1088 Rational Arithmetic

来源:微智科技网
#include<iostream>
#include<algorithm>
using namespace std;

struct fraction{
    long long up,down;
};

void show(fraction ans)
{
    int flag=0;
    if(ans.up==0)   printf("0");
    else{
        if(ans.up<0){
            printf("(");
            flag=1;
        }
        if(ans.down==1)     printf("%lld",ans.up);
        else if(abs(ans.up)>abs(ans.down))
            printf("%lld %lld/%lld",ans.up/ans.down,abs(ans.up)%abs(ans.down),ans.down);
        else
            printf("%lld/%lld",ans.up,ans.down);
        if(flag==1)     printf(")");
    }
}

long long (long long a,long long b)
{
    if(b==0)      return a;
    else          return (b,a%b);
}

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

fraction sum(fraction a,fraction b)
{
    fraction ans;
    ans.up=a.up*b.down+b.up*a.down;
    ans.down=a.down*b.down;
    ans=reduction(ans);
    show(a);
    printf(" + ");
    show(b);
    printf(" = ");
    show(ans);
    printf("\n");
}

fraction difference(fraction a,fraction b)
{
    fraction ans;
    ans.up=a.up*b.down-b.up*a.down;
    ans.down=a.down*b.down;
    ans=reduction(ans);
    show(a);
    printf(" - ");
    show(b);
    printf(" = ");
    show(ans);
    printf("\n");
}

fraction product(fraction a,fraction b)
{
    fraction ans;
    ans.up=a.up*b.up;
    ans.down=a.down*b.down;
    ans=reduction(ans);
    show(a);
    printf(" * ");
    show(b);
    printf(" = ");
    show(ans);
    printf("\n");
}

fraction quotient(fraction a,fraction b)
{
    fraction ans;
    ans.up=a.up*b.down;
    ans.down=a.down*b.up;
    ans=reduction(ans);
    show(a);
    printf(" / ");
    show(b);
    printf(" = ");
    if(b.up==0)     printf("Inf");
    else            show(ans);
    printf("\n");
}

int main()
{
    fraction a,b;
    scanf("%lld/%lld",&a.up,&a.down);
    scanf("%lld/%lld",&b.up,&b.down);
    a=reduction(a);
    b=reduction(b);
    sum(a,b);
    difference(a,b);
    product(a,b);
    quotient(a,b);
    return 0;
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 7swz.com 版权所有 赣ICP备2024042798号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务