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

这道题目应该很好理解,关键在于做法。
首先在于数据的取值范围,题目中只说明是整型,但没说多大,我因此有的样例点没有通过。
这道题需要使用long类型的数据格式。
话不多说,直接上代码。

//
//  main.cpp
//  1034 有理数四则运算 (20分)
//
//  Created by Zide Liu on 2020/1/22.
//  Copyright © 2020 Zide Liu. All rights reserved.
//

#include <iostream>
#include <string>
using namespace std;
long gcd(long a,long b){//辗转相除法
    return b?gcd(b,a%b):a;
}
    /*
可理解为
long gcd(long x,long y){
    int z=y;
    while(x%y){
        z=x%y;
        x=y;
        y=z;
    }
    return z;
}

    */

string print(long a,long b){
    long k1=gcd(a,b);
    a=a/k1;b=b/k1;
    if(a==0) return "0";
    string s;
    int judge=0;
    if(b<0){a=-a;b=-b;}
    if(a<0) {s.append("(-");a=-a;judge=1;}
    if(a>=b) s.append(to_string(a/b));
    if(a>=b&&a%b) s.insert(s.end(),' ');
    a=a%b;
    if(a){
        s.append(to_string(a));
        //s.append("/");
        s.insert(s.end(),'/');
        s.append(to_string(b));
    }
    if(judge) 
    //s.append(")");
    s.insert(s.end(),')');
    return s;
}
int main(){
    long a,b,c,d;
    scanf("%ld/%ld %ld/%ld",&a,&b,&c,&d);
    cout<<print(a,b)<<" + "<<print(c,d)<<" = "<<print(b*c+a*d,b*d)<<endl;
    cout<<print(a,b)<<" - "<<print(c,d)<<" = "<<print(a*d-b*c,b*d)<<endl;
    cout<<print(a,b)<<" * "<<print(c,d)<<" = "<<print(a*c,b*d)<<endl;
    b*c?cout<<print(a,b)<<" / "<<print(c,d)<<" = "<<print(a*d,b*c)<<endl:cout<<print(a,b)<<" / "<<print(c,d)<<" = Inf"<<endl;
    return 0;
}


相信看完代码你就明白了。
努力学习STL,会有不一样的风景

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务