1034. 有理数四则运算(20)||1088. Rational Arithmetic (20)

一开始写了400多行代码 提交 提示代码长度超限···无限蛋疼···重新构思逻辑 又一处bug 最后一测试点未过···对照网上的代码··检查后得知 分子分母相等时的情况未处理···

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;

typedef long long Type;

Type GCD(Type a,Type b)
{
      if( a>b )  swap( a, b );
      Type r = a%b;
      while(r)
      {
          a=b;
          b=r;
          r=a%b;
      }
      return b;
}

void print( Type a, Type b )
{
    if( a==0 ){
            cout<<0; return;
    }
    bool IsNegative = false;
    if( a<0 )  {
            IsNegative = true;
            a = -a;
    }
    Type Com = GCD( a, b );
    a = a/Com; b = b/Com;
    if( IsNegative ){
        if( a>b )
            if( b==1 ) cout<<"(-"<<a/b<<")";
            else         cout<<"(-"<<a/b<<" "<<a-a/b*b<<"/"<<b<<")";
        else if(a==b)
            cout<<"(-"<<a<<")";
        else
            cout<<"(-"<<a<<"/"<<b<<")";
    }
    else{
        if( a>b )
            if( b==1 ) cout<<a;
            else         cout<<a/b<<" "<<a-a/b*b<<"/"<<b;
        else if(a==b)
            cout<<a;
        else
            cout<<a<<"/"<<b;
    }
}

void add( Type a1, Type b1, Type a2, Type b2 )
{
    Type A, B;
    A = a1*b2 + a2*b1;
    B = b1*b2;
    print( a1, b1 );
    cout<<" + ";
    print( a2, b2 );
    cout<<" = ";
    print( A, B );
    cout<<endl;
}

void sub(Type a1, Type b1, Type a2, Type b2)
{
    Type A, B;
    A = a1*b2 - a2*b1;
    B = b1*b2;
    print( a1, b1 );
    cout<<" - ";
    print( a2, b2 );
    cout<<" = ";
    print( A, B );
    cout<<endl;
}

void mul( Type a1, Type b1, Type a2, Type b2 )
{
    Type A, B;
    A = a1*a2;
    B = b1*b2;
    print( a1, b1 );
    cout<<" * ";
    print( a2, b2 );
    cout<<" = ";
    print( A, B );
    cout<<endl;
}

void div( Type a1, Type b1, Type a2, Type b2 )
{
    print(a1,b1);
	printf(" / ");
	print(a2,b2);
	printf(" = ");
	if( a2==0 )
        cout<<"Inf";
    else{
        if( a2<0 ){
            a2 = -a2;
            b2 = -b2;
        }
        print( a1*b2, a2*b1 );
    }
    cout<<endl;
}

int main()
{
    Type a1, b1, a2, b2;
    scanf("%lld/%lld %lld/%lld",  &a1, &b1, &a2, &b2);
    add( a1, b1, a2, b2 );
    sub( a1, b1, a2, b2 );
    mul( a1, b1, a2, b2 );
    div( a1, b1, a2, b2 );
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值