PAT A1088 Rational Arithmetic

PAT A1088 Rational Arithmetic
其实就是一个简单的分数四则运算的题目,但是出现了几点我自己难以预料的错误,要引以为戒

  • 必须要用long long 型否则,进行乘法运算容易越界
  • //\ 我是打算简单的表示除法运算的但是如果后面紧跟一个函数,容易造成程序编译出错,这个排错用了很久
  • 在输出部分,分数的假分数表示,要注意第二个分母必须取正数,即用abs
  • 在输出部分,如果不用f=reduction(f);会导致没有返回,这个很奇怪,还没有想清楚
#include<cstdio>
#include<algorithm>
using namespace std;

struct Fraction{
    long long up,down;
};


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

Fraction reduction(Fraction f){
    if(f.up==0) f.down = 1;
    else if(f.down < 0){
        f.up = -f.up;
        f.down = -f.down;
    }
    long long t = gcd(abs(f.up),f.down);
    f.up /=t;
    f.down /=t;
    return f;
}
//+
Fraction sumf(Fraction a,Fraction b){
    Fraction result;
    result.up = a.up*b.down + b.up*a.down;
    result.down =a.down*b.down;
   
   return reduction(result);

}
//-
Fraction diff(Fraction a,Fraction b){
    Fraction result;


   result.up = a.up*b.down - b.up*a.down;
   result.down =a.down*b.down;

    return reduction(result); 

}
//*
Fraction prodf(Fraction a,Fraction b){
    Fraction result;
   result.up = a.up*b.up;
   result.down =a.down*b.down;
    return reduction(result);

}
//\

Fraction quof(Fraction a,Fraction b){
    Fraction result;
    result.up = a.up*b.down;
    result.down =a.down*b.up;
    return reduction(result);
}

void printfrc(Fraction f){
    f=reduction(f);
    if(f.up < 0)printf("(");
    
    if(f.down==1){
       printf("%lld" , f.up);
     }else if(f.down>abs(f.up)){
        printf("%lld/%lld",f.up,f.down);
    }else{
       printf("%lld %lld/%lld",f.up/f.down,abs(f.up)%f.down,f.down);
     }
     if(f.up < 0)printf(")");

    
}


int main(){
    Fraction a,b;
    scanf("%lld/%lld",&a.up,&a.down);
    scanf("%lld/%lld",&b.up,&b.down);
    //+
    printfrc(a);
    printf(" + ");
    printfrc(b);
    printf(" = ");
    printfrc(sumf(a,b));
    printf("\n");
    //-
    printfrc(a);
    printf(" - ");
    printfrc(b);
    printf(" = ");
    printfrc(diff(a,b));
    printf("\n");
    //*
    printfrc(a);
    printf(" * ");
    printfrc(b);
    printf(" = ");
    printfrc(prodf(a,b));
    printf("\n");
    //\
    
    printfrc(a);
    printf(" / ");
    printfrc(b);
    printf(" = ");
    if(b.up==0) printf("Inf");
    else printfrc(quof(a,b));
    printf("\n");
    return 0;
}
上一篇:用于检索的开源库


下一篇:A1088 Rational Arithmetic (20分)