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