字符串表达式解析与计算

编译原理学完了,想写一个解析数学表达式的程序

看网上的代码大多长且思路混乱

自己写了一个,基本原理是算符优先的归约法,所有函数写在了一个类里

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();
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值