📜  算法测验| SP竞赛3 |问题10

📅  最后修改于: 2021-06-28 22:15:17             🧑  作者: Mango

下面给出的是一个C++函数,用于评估表示为字符串的后缀表达式。下面的代码包含适当的注释,并且某些语句已特别标记。查找将导致错误输出的语句。

// C++ function to evaluate a given postfix expression
int evaluatePostfix(char* exp)
{
    // Create a stack of capacity equal to expression size
    stack st;
    int i;
   
    // Scan all characters one by one
    for (i = 0; exp[i]; ++i)
    {
        // If the scanned character is an operand (number here),
        // push it to the stack.
        // The isdigit() function is used to check if a particular 
        // character in the given input string is a digit or not.
        if (isdigit(exp[i]))
            st.push(exp[i]);    // Statement 1
   
        //  If the scanned character is an operator, pop two
        // elements from stack apply the operator
        else
        {
            int val1 = st.top();    // Statement 2
            st.pop();
            int val2 = st.top();
            st.pop();
              
            switch (exp[i])        // Statement 3            
            {
             case '+': st.push(val2 + val1); break;
             case '-': st.push(val2 - val1); break;
             case '*': st.push(val2 * val1); break;
             case '/': st.push(val2/val1);   break;
            }
        }
    }
      
    return st.top();
}

(A)陈述2
(B)陈述1
(C)陈述3和陈述1
(D)以上都不是答案: (B)
说明: https : //www.geeksforgeeks.org/stack-set-4-evaluation-postfix-expression/
这个问题的测验