評估字尾表示式


要對一個數學表示式求解,我們需要字首或字尾形式。將中綴轉換為字尾後,我們需要字尾求值演算法來求得正確的答案。

這裡我們也必須使用棧資料結構來求解字尾表示式。

根據字尾表示式,當發現了一些運算元後,將其推入棧中。當發現了一些運算子時,從棧中彈出兩個專案並按正確的順序執行運算。之後,也將結果推入棧中以供將來使用。在對整個表示式求值完成之後,最終結果也儲存在棧頂。

輸入和輸出

Input:
Postfix expression: 53+62/*35*+
Output:
The result is: 39

演算法

postfixEvaluation(postfix)

輸入:要進行求值的字尾表示式。

輸出:對字尾形式進行求值後的答案。

Begin
   for each character ch in the postfix expression, do
      if ch is an operator ⨀ , then
         a := pop first element from stack
         b := pop second element from the stack
         res := b ⨀ a
         push res into the stack
      else if ch is an operand, then
         add ch into the stack
   done
   return element of stack top
End

示例

#include<iostream>
#include<cmath>
#include<stack>
using namespace std;

float scanNum(char ch) {
   int value;
   value = ch;
   return float(value-'0');   //return float from character
}

int isOperator(char ch) {
   if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^')
      return 1;    //character is an operator
   return -1;   //not an operator
}

int isOperand(char ch) {
   if(ch >= '0' && ch <= '9')
      return 1;    //character is an operand
   return -1;   //not an operand
}

float operation(int a, int b, char op) {
   //Perform operation
   if(op == '+')
      return b+a;
   else if(op == '-')
      return b-a;
   else if(op == '*')
      return b*a;
   else if(op == '/')
      return b/a;
   else if(op == '^')
      return pow(b,a);    //find b^a
   else
      return INT_MIN;    //return negative infinity
}

float postfixEval(string postfix) {
   int a, b;
   stack<float> stk;
   string::iterator it;

   for(it=postfix.begin(); it!=postfix.end(); it++) {
      //read elements and perform postfix evaluation
      if(isOperator(*it) != -1) {
         a = stk.top();
         stk.pop();
         b = stk.top();
         stk.pop();
         stk.push(operation(a, b, *it));
      }else if(isOperand(*it) > 0) {
         stk.push(scanNum(*it));
      }
   }
   return stk.top();
}

main() {
   string post = "53+62/*35*+";
   cout << "The result is: "<<postfixEval(post);
}

輸出

The result is: 39

更新於:2020 年 6 月 17 日

8K+ 瀏覽

開啟你的 職業

完成課程即可獲得認證

開始吧
廣告
© . All rights reserved.