编译原理学完了,想写一个解析数学表达式的程序
看网上的代码大多长且思路混乱
自己写了一个,基本原理是算符优先的归约法,所有函数写在了一个类里
calc函数即可计算
#include<stack>
#include<map>
using namespace std;
class StrParse {
public:
map<char, int> prio;
StrParse() {
prio['+'] = prio['-'] = 1;//优先关系应是一个矩阵,这里做了简化,仅仅定义了优先级
prio['*'] = prio['/'] = 2;
prio['('] = 3, prio[')'] = 0;
prio['#'] = -1;
}
int calc_op(int n1, int n2, char op) {
switch (op) {
case '+':return n1 + n2;
case '-':return n1 - n2;
case '*':return n1 * n2;
case '/':return n1 / n2;
}
return -1;
}
int calc(const char* str) {
int carr = 1, num = 0; bool isNum = false;
stack<int>nums; stack<char>ops; ops.push('#');
for (int i = 0; str[i]; i++) {
if (str[i] >= '0'&&str[i] <= '9') { num = num * carr + str[i] - '0'; carr *= 10; isNum = true; }
else {
if (isNum) { nums.push(num); num = 0; carr = 1; isNum = false; }
while (prio[ops.top()] > prio[str[i]]) {
if (ops.top() == '('&&str[i] == ')') { ops.pop(); break; }//相当于括号的归约(num)
if (ops.top() == '(') break;//+-*/遇(不能消去,即(与+-*/的优先级的关系为相等
int n1 = nums.top(); nums.pop();
int n2 = nums.top(); nums.pop();//相当于数字的归约过程(num op num)
nums.push(calc_op(n2, n1, ops.top())); ops.pop();
}
if (str[i] != ')')ops.push(str[i]);
}
}
return nums.top();
}
};