#include <iostream>
#include <string>
#include <stack>
#include <sstream>
using namespace std;
stack<int>aStack;
stack<int>operand1;
stack<int>operand2;
stringstream postfix;
stringstream &postfixExp(string ch)
{
for(int i =0; i< ch.length(); i++)
{
if(ch[i] == '1' || ch[i] == '2' || ch[i] == '3' || ch[i] == '4' || ch[i] == '5' || ch[i] == '6' || ch[i] == '7' || ch[i] == '8' || ch[i] == '9' || ch[i] == '0' )
{
aStack.push(ch[i]);
}
else if(ch[i] == '+')
{
operand1.push(aStack.top());
aStack.pop();
operand2.push(aStack.top());
aStack.pop();
int x = operand1.top() - 48;
int y = operand2.top() - 48;
int result = x + y;
aStack.push(result);
}
else if(ch[i] == '*')
{
operand1.push(aStack.top());
aStack.pop();
operand2.push(aStack.top());
aStack.pop();
int x = operand1.top() - 48;
int y = operand2.top() - 48;
int result = x * y;
aStack.push(result);
}
}
postfix << aStack.top();
return postfix;
}
int main()
{
string postfix = "32+2*";
stringstream * result = &postfixExp(postfix);
cout << result-> str() ;
return 0;
}
嗨,有人知道我上面的代码有什么问题吗?我的程序应该返回一个后缀符号的值。我输入“32+2*”作为后缀符号,它应该返回 10。显然出了点问题,它返回 -86
我想错误来自这个特定的代码
else if(ch[i] == '*')
{
operand1.push(aStack.top());
aStack.pop();
operand2.push(aStack.top());
aStack.pop();
int x = operand1.top() - 48;
int y = operand2.top() - 48;
int result = x * y;
aStack.push(result);
}
从那里,我显示了操作数 2,它显示 -43 而不是 7(源自之前添加的“34+”)
请让我知道哪一部分错了,为什么我的操作数 2 的值不是 7。
谢谢