PostFix表达式评估

时间:2014-03-23 07:48:12

标签: c++ evaluation postfix-notation

我正在编写一个C ++程序来评估PostFIx表达式。这是以下代码:

#include <iostream>
#include <string>
#include <stack>
#include <conio.h>

using namespace std;

int operand1;
int operand2;

bool operator_test(char character){ //to test whether its an operator or not
    if(character=='+' || character=='-' || character=='*' || character=='/')
        return true;
    else
        return false;
}

bool operand_test(char character){ //to test whether its an operand or not
    if(!operator_test(character) && character!='(' && character!=')')
            return true;
    else
        return false;
}

int DoOperation(char operation,int operand1,int operand2){
    if(operation=='+') return operand1+operand2;
    else if(operation=='-') return operand1-operand2;
    else if(operation=='*') return operand1*operand2;
    else if(operation=='/') return operand1/operand2;
}


int main(){
    string expression;
    cout<<"ENTER POSTFIX EXPRESSION"<<endl;
    cin>>expression;
    stack<int>test_stack;
    int result;
    for(int i=0;i<expression.length();i++){

        if(operand_test(expression[i]))
            test_stack.push(expression[i]);
        else if(operator_test(expression[i]))
            operand2=test_stack.top();

        test_stack.pop();
        operand1=test_stack.top();
        test_stack.pop();
        result=DoOperation(expression[i],operand1,operand2);
        test_stack.push(result);
    }

    cout<<"EVALUATION: "<<test_stack.top()<<endl;
    getch();
    return 0;
}

如果我输入23+,则应输出5作为输出。但它给了51.我在这里做错了什么? 提前谢谢

1 个答案:

答案 0 :(得分:0)

在我的头脑中,你的代码在几个部门都缺乏:

正如@ChristianAichinger已经指出的那样,它的格式很糟糕。这是一个缺陷,因为你和其他任何人都无法阅读它。

你的else if没有打开一个块,因此只对下一个语句operand2=test_stack.top();进行操作,而不是跟随它的整个部分。正确的格式化会更明显。

您的代码中没有任何部分可以解析整数。因此,您的代码缺少其功能的主要部分。

可能存在更多错误,但只要代码处于这种状态,分析就相当困难。

相关问题