【发布时间】:2016-06-19 06:58:51
【问题描述】:
我是 C++ 新手,我想使用堆栈来评估作为输入给出的表达式(例如 2+3*5+4),它只包含数字、+ 和 *。我写了这段代码,但它给了我分段错误:11.你能帮我解决这个问题,或者给我一个提示可能是什么问题吗?谢谢! (我注意到这个网站上有类似的问题,但我无法用它们来解决我的问题)
#include <iostream>
#include <stack>
using namespace std;
bool highPrecedence(char a, char b){
if((a=='+')&&(b=='*'))
return true;
return false;
}
int main()
{
char c = 'a';
double x;
stack<char> stack;
double v[10];
int i=0;
double res;
while(true)
{
c = cin.get();
if(c=='\n'){
while(stack.size()!=0){
if (stack.top()=='*'){
double res = v[i]*v[i-1];
i--;
v[i]=res;
stack.pop();
}
if (stack.top()=='+'){
res = v[i]+v[i-1];
i--;
v[i]=res;
stack.pop();
}
}
break;
}
if ( '0'<=c && c<='9' )
{
cin.putback(c);
cin>>x;
cout<<"Operand "<<x<<endl;
i=i+1;
v[i]=x;
}
else
{
if(c!=' ') cout<< "Operator " <<c<<endl;
if (stack.size()==0)
stack.push(c);
else{
while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){
if (stack.top()=='*'){
double res = v[i]*v[i-1];
i--;
v[i]=res;
stack.pop();
}
if (stack.top()=='+'){
res = v[i]+v[i-1];
i--;
v[i]=res;
stack.pop();
}
}
stack.push(c);
}
}
}
cout<<v[0]<<endl;
}
【问题讨论】:
-
你用过调试器吗?
-
请发布minimal reproducible example,而不是您的所有代码。链接页面包含有关如何创建的帮助。
-
@MikeCAT 嗯不确定。我使用 Xcode 和终端
-
2+3*5+4- 这是中缀表示法 - 不是后缀 - 查看反向波兰语 -
@EdHeal 是的,我最初在中缀中,我需要转换为后缀然后评估它