C++ 计算后缀

C++ 计算后缀,c++,stack,C++,Stack,我的代码假设计算后缀表达式的值。但是我被困在“结果”上,我不知道如何编写代码。我写了:result=operand1 operation.push operand2,逻辑上将给出一个错误。我用了两个堆栈 int main() { string input; cout << "Enter a postfix expression: " << endl; getline(cin, input); double operand1, opera

我的代码假设计算后缀表达式的值。但是我被困在“结果”上,我不知道如何编写代码。我写了:result=operand1 operation.push operand2,逻辑上将给出一个错误。我用了两个堆栈

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;
}
intmain()
{
字符串输入;

cout您需要在运算符上进行
切换
,然后自己计算结果:

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;
}

首先,您只需要一个堆栈

然后是表情

结果=操作数1操作。推送操作数2

看起来不像我知道的任何后缀,相反,我期待着类似的东西

operand1 operand2 operator
因此,将操作数推送到堆栈上,每当找到运算符时,就会弹出堆栈上最上面的两个项并推送到结果

e、 g

然后在计算它时(伪代码)


事实上,它的操作数2+操作数1不正确。后缀是
34+
,因此在堆栈上
43
。在OP的代码中,操作数2
首先从堆栈中提取。我将代码更改为:'开关(操作数1,操作数2){case'+':result=operan1+operan2;break;case'-':result=operan1-operan2;break;case'*':result=operan1*operan2;break;case'/':result=operan1/operan2;break;}operation.push(result);}'但只有-sign给出正确答案。
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]