PAT甲题题解-1088. Rational Arithmetic (20)-模拟分数计算
输入为两个分数,让你计算+,-,*,\四种结果,并且输出对应的式子,分数要按带分数的格式k a/b输出
如果为负数,则带分数两边要有括号
如果除数为0,则式子中的结果输出Inf
模拟题最好自己动手实现,考验细节处理,其它没啥好说的。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; long long numerator[2]; long long denominator[2]; long long GCD(long long a,long long b){ a=abs(a); b=abs(b); if(b==0) return a; return GCD(b,a%b); } struct Fraction{ long long integer; long long numerator; long long denominator; }frac[3]; /** 转化成带分数的形式 */ void transfer(long long numerator,long long denominator,int i){ //long long gcd=GCD(numerator,denominator); //numerator=numerator/gcd; //denominator=denominator/gcd; frac[i].integer=numerator/denominator; frac[i].numerator=numerator%denominator; frac[i].denominator=denominator; } /** 输出,如果为负数还要有括号 */ void print(Fraction f){ if(f.integer!=0){ if(f.integer<0) printf("("); printf("%lld",f.integer); } if(f.numerator!=0){ if(f.integer!=0){ printf(" "); } //如果前面整数部分为0,则这里需要加( else if(f.numerator<0) printf("(-"); //注意,如果是负数,只要整数前面一个'-'就可以,所以这里不需要'-' if(f.numerator>0) printf("%lld/%lld",f.numerator,f.denominator); else printf("%lld/%lld",-f.numerator,f.denominator); } if(f.integer==0&&f.numerator==0) printf("0"); else if(f.integer<0 || f.numerator<0) printf(")"); //末尾补) } int main() { long long res; scanf("%lld/%lld %lld/%lld",&numerator[0],&denominator[0],&numerator[1],&denominator[1]); //先约分 long long gcd0=GCD(numerator[0],denominator[0]); numerator[0]=numerator[0]/gcd0; denominator[0]=denominator[0]/gcd0; long long gcd1=GCD(numerator[1],denominator[1]); numerator[1]=numerator[1]/gcd1; denominator[1]=denominator[1]/gcd1; long long gcd=GCD(denominator[0],denominator[1]); long long lcm=(denominator[0]/gcd)*gcd*(denominator[1]/gcd); transfer(numerator[0],denominator[0],0); transfer(numerator[1],denominator[1],1); //sum long long sum=numerator[0]*(lcm/denominator[0])+numerator[1]*(lcm/denominator[1]); long long gcd2=abs(GCD(sum,lcm)); transfer(sum/gcd2,lcm/gcd2,2); print(frac[0]); printf(" + "); print(frac[1]); printf(" = "); print(frac[2]); printf("\n"); //difference sum=numerator[0]*(lcm/denominator[0])-numerator[1]*(lcm/denominator[1]); gcd2=abs(GCD(sum,lcm)); transfer(sum/gcd2,lcm/gcd2,2); print(frac[0]); printf(" - "); print(frac[1]); printf(" = "); print(frac[2]); printf("\n"); //product sum=numerator[0]*numerator[1]; res=denominator[0]*denominator[1]; gcd2=abs(GCD(sum,res)); transfer(sum/gcd2,res/gcd2,2); print(frac[0]); printf(" * "); print(frac[1]); printf(" = "); print(frac[2]); printf("\n"); //quotient print(frac[0]); printf(" / "); print(frac[1]); printf(" = "); if(numerator[1]==0){ printf("Inf\n"); } else{ sum=numerator[0]*denominator[1]; res=denominator[0]*numerator[1]; if(res<0){ sum=-sum; res=-res; } gcd2=abs(GCD(sum,res)); transfer(sum/gcd2,res/gcd2,2); print(frac[2]); printf("\n"); } return 0; }