我的代码假定计算后缀表达式的值。但是我被“结果”所困,我不知道如何写代码。我写道: result = operand1 operation.push operand2,逻辑上会给出一个错误。我使用了2堆栈。
int main()
{
string input;
cout << "Enter a postfix expression: " << endl;
getline(cin, input);
double operand1, operand2, result;
stack<double> number;
stack<char>operation;
int i=0;
while (i < input.length())
{
if (input[i] == '+' || input[i] == '-' || input[i] == '*' || input[i] == '/' || input[i] == '^')
operation.push(input[i]);
else
number.push(input[i]);
i++;
}
operand2 = number.top( );
number.pop( );
operand1 = number.top( );
number.pop( );
result = operand1 operation.push(input[i]) operand2
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return 0;
}有没有人能建议一个更好的解决方案?谢谢
发布于 2011-04-11 21:44:46
你需要在运算符上做一个switch,然后自己计算结果:
char op = operation.top();
switch( op ) {
case '+': result = operand1 + operand2; break;
case '-': result = operand1 - operand2; break;
case '*': result = operand1 * operand2; break;
case '/': result = operand1 / operand2; break;
case '^': result = pow(operand1, operand2) ; break;
}发布于 2011-04-11 21:51:21
首先,您只需要一个堆栈
然后,表达式
结果= operand1 operation.push operand2
看起来不像我知道的任何后缀,相反,我希望是这样的
operand1 operand2 operator所以你把操作数压入堆栈,每当你找到一个运算符,你就把堆栈最上面的两个项目弹出并压入结果。
例如:
infix 10 * ( 12 + 15 ) -> postfix 12 15 + 10 *然后在评估它时(伪代码)
push -> 12 [operand]
push -> 15 [operand]
pop -> + [operator]
push result 12+15 [operand]
push 10 [operand]
pop -> * [operator]
push result 27*10 [operand]https://stackoverflow.com/questions/5622099
复制相似问题