评估PostFix功能

时间:2016-04-21 04:03:28

标签: c++ stack postfix-notation

下面我正在尝试编写一个评估后缀表达式的程序。但是,我注意到我设置要操作的两个元素没有设置为正确的值。我还在学习c ++库中的堆栈功能,所以如果有人能解释为什么会这样,我会非常感激!

/*Sample output:
Enter an infix or prefix expression:3+4-1
Postfix is: 34+1-
postFix[i]: 3
postFix[i]: 4
element1: 52
element2: 51
val is: 103
postFix[i]: 1
element1: 49
element2: 103
val is: 54
Value is 54*/

int evaluatePostfix (string postFix)
{
     stack<int> operands;

        int length = postFix.length();
        int val = 0;
        for ( int i = 0; i < length; i++ )
        {
                //if the char is a digit push the digit onto the stack
                if( isdigit( postFix[i] ))
                {
                        operands.push( postFix[i] );
                        cout << "postFix[i]: " << postFix[i] << endl;
                }
                else if ( isOperator(postFix[i]) )
                {
                        //
                        //element 1 and element 2 will be the element on the top of the stack
                        //
                        int element1 = operands.top();
                        cout << "element1: " << element1 << endl;
                        operands.pop();
                        int element2 = operands.top();
                        cout << "element2: " << element2 << endl;
                        operands.pop();
                        //
                        //create a switch statement that evaluates the elements based on the operator
                        //
                        switch( postFix[i] )
                        {
                                case '+':
                                        val = element2 + element1;
                                        cout << "val is: " << val << endl;
                                        operands.push(val);
                                        break;
                                case '-':
                                        val = element2 - element1;
                                        cout << "val is: " << val << endl;
                                        operands.push(val);
                                        break;
                                case '*':
                                        val = element2 * element1;
                                        operands.push(val);
                                        break;
                                case '/':
                                        val = element2 / element1;
                                        operands.push(val);
                                        break;
                                default:
                                        return 0;
                        }

                                                                                 }

        }
        return val;
}

1 个答案:

答案 0 :(得分:0)

问题是你的postfix是一个字符串,当你按下那些字符(有效整数)时,你会得到ascii值(例如51,52)。那些对应于正确的数字(例如3,4)

你最终得到的是一个偏移48的值,它对应于0符号。