题目链接
1.单独写一个函数ration来传入分子和分母,输出为给定要求的 k a/b的格式即可,if-else比较多,但是思路不难,因此需要快动手;计算得到±*/中间值也是传给ration来输出;
2.因为乘积可能overflow,因此需要定义long long;
3.注意审清题目:分母为0输出Inf 而不是inf ,一定要仔细!
4.还有牛客网报如下错,可能的原因是本应该有返回值的函数没有写return语句造成的,在本地及PTA上都能过,但是牛客OJ过不了qwq
段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起
ration函数
详解注释:
void ration(LL a1,LL b1){
LL sign;//标记符号
if(a1<0) sign=-1;
else sign=1;
a1=abs(a1);//都用绝对值进行计算
LL zheng1=a1/b1;//整数部分
a1=a1%b1;//真分数的分子
if(a1!=0){// 比如4/2,真分数的分子为0,因此要小心这里求最大公约数要讨论
LL yue1=lcm(a1,b1);
a1=a1/yue1;
b1=b1/yue1;
}
if(zheng1!=0){
if(sign==-1){//要不是因为负数需要括起来,也不必这么多if-else了
if(a1!=0)
cout << "(" << sign*zheng1 << " " << a1 << "/" << b1 << ")";
else cout << "(" << sign*zheng1 << ")";
}else{
if(a1!=0)
cout << sign*zheng1 << " " << a1 << "/" << b1 ;
else cout << sign*zheng1 ;
}
}else if(zheng1==0){
if(sign==-1){
if(a1!=0)
cout << "(" << sign* a1 << "/" << b1 << ")";
else cout << 0;
}else{
if(a1!=0)
cout << sign * a1 << "/" << b1;
else cout << 0;
}
}
·
·
·
·
·
·
完整代码:
#include <iostream>
#include <cstdio>
typedef long long LL;
using namespace std;
void ration(LL a1,LL b1);
LL lcm(LL a,LL b);//求a和b的最大公约
int main() {
LL a1,b1,a2,b2;
scanf("%lld/%lld %lld/%lld",&a1,&b1,&a2,&b2);
ration(a1,b1);
cout << " + " ;
ration(a2,b2);
cout << " = ";
LL bei=b1*b2/lcm(b1,b2);
ration(a1*(bei/b1)+a2*(bei/b2),bei);
cout << endl;
ration(a1,b1);
cout << " - " ;
ration(a2,b2);
cout << " = ";
ration(a1*(bei/b1)-a2*(bei/b2),bei);
cout << endl;
ration(a1,b1);
cout << " * " ;
ration(a2,b2);
cout << " = ";
ration(a1*a2,b1*b2);
cout << endl;
ration(a1,b1);
cout << " / " ;
ration(a2,b2);
cout << " = ";
if(a2==0) cout << "Inf";
else{
if(a2<0){//因为相除的时候第二个分数要颠倒,为了统一在分子处理符号,这里颠倒一下符号,这样a1*b2就包含符号运算了
a2=-a2;
b2=-b2;
}
ration(a1*b2,b1*a2);
}
return 0;
}
LL lcm(LL a,LL b){//求a和b的最大公约数
//若一正一负按照两个正求
a=abs(a);
b=abs(b);
LL big=a>b?a:b;
LL small=a<b?a:b;
LL r=big%small;
while(r){
big=small;
small=r;
r=big%small;
}
return small;
}
void ration(LL a1,LL b1){
LL sign;
if(a1<0) sign=-1;
else sign=1;
a1=abs(a1);
LL zheng1=a1/b1;
a1=a1%b1;
if(a1!=0){
LL yue1=lcm(a1,b1);
a1=a1/yue1;
b1=b1/yue1;
}
if(zheng1!=0){
if(sign==-1){
if(a1!=0)
cout << "(" << sign*zheng1 << " " << a1 << "/" << b1 << ")";
else cout << "(" << sign*zheng1 << ")";
}else{
if(a1!=0)
cout << sign*zheng1 << " " << a1 << "/" << b1 ;
else cout << sign*zheng1 ;
}
}else if(zheng1==0){
if(sign==-1){
if(a1!=0)
cout << "(" << sign* a1 << "/" << b1 << ")";
else cout << 0;
}else{
if(a1!=0)
cout << sign * a1 << "/" << b1;
else cout << 0;
}
}
}