简单计算器遇到段错误,要哭了
用cpp实现一个简单计算器,在本地测试用例都很好,以提交就提示段错误,各路大佬们帮帮忙把
#include<stdio.h>
#include<stack>
#include<string.h>
#include<iostream>
using namespace std;
bool cmp(char ch1,char ch2)
{
if((ch1=='*'&&ch2=='/')||(ch1=='*'&&ch2=='/'))
return 1;
else if((ch1=='*'||ch1=='/')&&(ch2=='+'||ch2=='-'))
return 1;
else if((ch1=='+'||ch1=='-')&&(ch2=='*'||ch2=='/'))
return 0;
else if((ch1=='+'&&ch2=='-')||(ch1=='-'&&ch2=='+'))
return 1;
return 1;
}
double caculate(double a,double b,char ch)
{
if(ch=='*')
return a*b;
else if(ch=='/'&&b!=0)
return a/b;
else if(ch=='-')
return a-b;
else if(ch=='+')
return a+b;
return 0;
}
int main()
{
char str[201];
stack<double> sn;//数字
stack<char> sc;//符号
while(gets(str))
{
if(!strcmp(str,"0"))
break;
while(!sn.empty())
sn.pop();
while(!sc.empty())
sc.pop();
for(int i=0;i<strlen(str);)
{
if(str[i]>='0'&&str[i]<='9')
{
int num=0;
while(str[i]!=' '&&str[i]!='\0'&&i<strlen(str))
{
num=num*10+(str[i]-'0');
i++;
}
sn.push(num);
i++;
}
else
{
if(sc.empty())
{
sc.push(str[i]);
i+=2;
}
else
{
while(!cmp(str[i],sc.top())&&!sc.empty())
{
char ch=sc.top();
sc.pop();
double b=sn.top();
sn.pop();
double a=sn.top();
sn.pop();
double ans=caculate(a,b,ch);
sn.push(an***r /> }
sc.push(str[i]);
i+=2;
}
}
}
while(!sc.empty())
{
char ch=sc.top();
sc.pop();
double b=sn.top();
sn.pop();
double a=sn.top();
sn.pop();
sn.push(caculate(a,b,ch));
}
printf("%.2lf\n",sn.top());
}
return 0;
}
#笔试题目##include<stack>
#include<string.h>
#include<iostream>
using namespace std;
bool cmp(char ch1,char ch2)
{
if((ch1=='*'&&ch2=='/')||(ch1=='*'&&ch2=='/'))
return 1;
else if((ch1=='*'||ch1=='/')&&(ch2=='+'||ch2=='-'))
return 1;
else if((ch1=='+'||ch1=='-')&&(ch2=='*'||ch2=='/'))
return 0;
else if((ch1=='+'&&ch2=='-')||(ch1=='-'&&ch2=='+'))
return 1;
return 1;
}
double caculate(double a,double b,char ch)
{
if(ch=='*')
return a*b;
else if(ch=='/'&&b!=0)
return a/b;
else if(ch=='-')
return a-b;
else if(ch=='+')
return a+b;
return 0;
}
int main()
{
char str[201];
stack<double> sn;//数字
stack<char> sc;//符号
while(gets(str))
{
if(!strcmp(str,"0"))
break;
while(!sn.empty())
sn.pop();
while(!sc.empty())
sc.pop();
for(int i=0;i<strlen(str);)
{
if(str[i]>='0'&&str[i]<='9')
{
int num=0;
while(str[i]!=' '&&str[i]!='\0'&&i<strlen(str))
{
num=num*10+(str[i]-'0');
i++;
}
sn.push(num);
i++;
}
else
{
if(sc.empty())
{
sc.push(str[i]);
i+=2;
}
else
{
while(!cmp(str[i],sc.top())&&!sc.empty())
{
char ch=sc.top();
sc.pop();
double b=sn.top();
sn.pop();
double a=sn.top();
sn.pop();
double ans=caculate(a,b,ch);
sn.push(an***r /> }
sc.push(str[i]);
i+=2;
}
}
}
while(!sc.empty())
{
char ch=sc.top();
sc.pop();
double b=sn.top();
sn.pop();
double a=sn.top();
sn.pop();
sn.push(caculate(a,b,ch));
}
printf("%.2lf\n",sn.top());
}
return 0;
}