首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >评估后缀

评估后缀
EN

Stack Overflow用户
提问于 2011-04-11 21:33:36
回答 2查看 1.3K关注 0票数 0

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

代码语言:javascript
复制
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;
}

有没有人能建议一个更好的解决方案?谢谢

EN

回答 2

Stack Overflow用户

发布于 2011-04-11 21:44:46

你需要在运算符上做一个switch,然后自己计算结果:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2011-04-11 21:51:21

首先,您只需要一个堆栈

然后,表达式

结果= operand1 operation.push operand2

看起来不像我知道的任何后缀,相反,我希望是这样的

代码语言:javascript
复制
operand1 operand2 operator

所以你把操作数压入堆栈,每当你找到一个运算符,你就把堆栈最上面的两个项目弹出并压入结果。

例如:

代码语言:javascript
复制
infix 10 * ( 12 + 15 ) -> postfix 12 15 + 10 *

然后在评估它时(伪代码)

代码语言:javascript
复制
push -> 12 [operand]
push -> 15 [operand]
pop -> +   [operator]
push result 12+15 [operand]
push 10 [operand]
pop -> *  [operator]
push result 27*10 [operand]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5622099

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档