目标是编写一个程序来解决后修复/反向波兰表示法表达式。这似乎是一件容易的事,但我似乎忽略了其中的错误。在此先感谢您的帮助。
vector<int> stack;
string input;
cout << "Please enter post-fix expression to be evaluated (+, -, *, /): ";
cin >> input;
for(int i=0; i<input.size(); i++)
{
if(input[i] == '+')
{
int temp1 = stack.back();
stack.pop_back();
int temp2 = stack.back();
stack.pop_back();
int sum = temp1 + temp2;
stack.push_back(sum);
}
else if(input[i] == '-')
{
int temp1 = stack.back();
stack.pop_back();
int temp2 = stack.back();
stack.pop_back();
int difference = temp1 - temp2;
stack.push_back(difference);
}
else if(input[i] == '*')
{
int temp1 = stack.back();
stack.pop_back();
int temp2 = stack.back();
stack.pop_back();
int product = temp1 * temp2;
stack.push_back(product);
}
else if(input[i] == '/')
{
int temp1 = stack.back();
stack.pop_back();
int temp2 = stack.back();
stack.pop_back();
int quotient = temp1 / temp2;
stack.push_back(quotient);
}
else
{
stack.push_back(input[i]);
}
}
cout << "Result: " << stack.back();
最佳答案
真正的问题是 stack.push_back(input[i]);您推回一个字符,例如“7”,这将导致 55 被压入堆栈。
关于c++ - 后置表达式求解器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26475891/