#,表達式以 # 結尾| 運算符 | 左優先級 | 右優先級 |
|---|---|---|
| = | 0 | 0 |
| ( | 1 | 6 |
| * / | 5 | 4 |
| + - | 3 | 2 |
| ) | 6 | 1 |
左優先級用於棧內元素,右優先級用於輸入元素。相等時彈出(左結合)。
#include <iostream>
using namespace std;
#define MaxSize 100
#define MaxOp 7
struct OpInfo { char ch; int pri; };
OpInfo lpri[MaxOp] = {{'=',0},{'(',1},{'*',5},{'/',5},{'+',3},{'-',3},{')',6}};
OpInfo rpri[MaxOp] = {{'=',0},{'(',6},{'*',4},{'/',4},{'+',2},{'-',2},{')',1}};
int leftpri(char op) { for(int i=0;i> exp;
trans(exp, postexp);
cout << "後綴: " << postexp << endl;
cout << "結果: " << calculate(postexp) << endl;
return 0;
}
輸入: 3+4*2/(1-5) 後綴: 3#4#2#*1#5#-/#+ 結果: 1
std::stack、std::string、std::stod雙棧法是編譯原理、解析器構建的基石算法,值得徹底掌握。