表达式求值

来源:互联网 发布:天猫推荐算法大赛代码 编辑:程序博客网 时间:2024/06/10 14:09
#include <iostream>#include <stack>#include <string>#include <cctype>using namespace std;class Expression {private:string exp;stack<char> st;stack<int> res;public:void init();int calculate();int cal(int a, int b, char flag);bool isNumber(char c);bool priorityIsHigher(char a, char b);};int Expression::cal(int a, int b, char flag) {switch (flag) {case '+':return a + b;break;case '-':return a - b;break;case '*':return a * b;break;case '/':return a / b;break;}return 0;}int Expression::calculate() {bool flag;int value = 0;int a, b, result;for (string::iterator iter = exp.begin(); iter != exp.end(); iter++) {if (isNumber(*iter)) {value = value*10 + *iter - 48;flag = true;} else {if (flag) {res.push(value);flag = false;value = 0;}if (*iter == '(') {st.push(*iter);} else if (*iter == ')') {while(!st.empty() && st.top() != '(') {a = res.top();res.pop();b = res.top();res.pop();result = cal(b, a, st.top());st.pop();res.push(result);}st.pop();} else if (*iter == ' ') {continue;} else {if (!st.empty() && st.top() == '(') {st.push(*iter);} else {while (!st.empty() && !priorityIsHigher(*iter, st.top())) {a = res.top();res.pop();b = res.top();res.pop();result = cal(b, a, st.top());st.pop();res.push(result);}st.push(*iter);}}}}if (flag) {res.push(value);}while (!st.empty()) {a = res.top();res.pop();b = res.top();res.pop();result = cal(b, a, st.top());st.pop();res.push(result);}return res.top();}bool Expression::priorityIsHigher(char a, char b) {if (b == '(') {return true;}if ((a == '*' || a== '/') && (b == '+' || b == '-')) {return true;}return false;}bool Expression::isNumber(char c) {return isdigit(c);}void Expression::init() {std::cout << "enter an expression:";getline(std::cin, exp);//std::cout << exp;}int main() {Expression *e = new Expression();e->init();std::cout << e->calculate();return 0;}
输入:3 + 9 - (2*3) + 10/5
0 0