1088. Rational Arithmetic (20)

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>

#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <map>
#include <set>

using namespace std;

struct node
{
    long long  up;
    long long down;
};

long long gcd(long a,long b)
{
    a=abs(a);
    b=abs(b);
    while(a%b!=0)
    {
        long long t=a%b;
        a=b;
        b=t;
    }

    return b;
}

node reduct(node a)
{
    long long t=gcd(a.up,a.down);
    a.up/=t;
    a.down/=t;

    return a;
}

node add(node a,node b)
{
    node tnode;
    tnode.up=b.down*a.up+a.down*b.up;
    tnode.down=a.down*b.down;
    tnode=reduct(tnode);//化简

    return tnode;
}

node dif(node a,node b)
{
    node tnode;
    tnode.up=a.up*b.down-b.up*a.down;
    tnode.down=a.down*b.down;
    tnode=reduct(tnode);

    return tnode;
}


node pro(node a,node b)
{
    node tnode;
    tnode.up=a.up*b.up;
    tnode.down=a.down*b.down;
    tnode=reduct(tnode);

    return tnode;
}


node qua(node a,node b)
{
    node tnode;
    tnode.up=a.up*b.down;
    tnode.down=a.down*b.up;
    tnode=reduct(tnode);

    if(tnode.up<0&&tnode.down<0)
    {
        tnode.up=-tnode.up;
        tnode.down=-tnode.down;
    }
    else if(tnode.up>0 && tnode.down<0)
    {
        tnode.up=-tnode.up;
        tnode.down=-tnode.down;
    }

    return tnode;
}

void show(node a)
{
    a=reduct(a);

    if(a.up<0)
        printf("(");

    if(a.up==0)
        printf("0");
    else
    if(abs(a.up)<a.down)
    {
        printf("%lld/%lld",a.up,a.down);
    }
    else if(abs(a.up)==a.down)
    {
        printf("%lld",a.up/a.down);
    }
    else//假分数
    {
        if(a.up%a.down==0)
            printf("%lld",a.up/a.down);
        else
            printf("%lld %lld/%lld",a.up/a.down,abs(a.up)%a.down,a.down);//***abs?
    }

    if(a.up<0)
        printf(")");
}

int main()
{
  //  freopen("in.txt","r" ,stdin);

    node node1,node2;
    scanf("%lld/%lld %lld/%lld",&node1.up,&node1.down,&node2.up,&node2.down);

    show(node1); printf(" + "); show(node2); printf(" = "); show(add(node1,node2)); printf("\n");
    show(node1); printf(" - "); show(node2); printf(" = "); show(dif(node1,node2)); printf("\n");
    show(node1); printf(" * "); show(node2); printf(" = "); show(pro(node1,node2)); printf("\n");

    if(node2.up==0)
    {
        show(node1); printf(" / "); show(node2); printf(" = "); printf("Inf");
    }
    else
    {
        show(node1); printf(" / "); show(node2); printf(" = "); show(qua(node1,node2));
    }

    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值