四则运算-表达式求值

思路:

1。先把输入的表达式转成后缀表达式。

2。之后通过对后缀表达式进行计算结果

 

代码如下:

//写一个包含(),+,-,*,/等操作符的表达式计算,之后想想测试用例 /* 输入 12*(1+2*3+4-5) 输出计算结果72 如果要对输入的表达进行合法性检查,那么可以用四则运算的正则表达式来完成合法性判断, 这样就用到了boost中关于正则表达式的判断部分。 */ #include <iostream> #include <string> #include <vector> #include <stack> using namespace std; char operat[] = "+-*/()"; string input; vector<string> midarray; vector<string> parray; /*解析表达式的目的, 例如输入 12*(1+2*3+4-5) 这么一个表达式: 返回一个元素是string的vector: 12 * ( 1 + 2 * 3 + 4 - 5 ) 称为中缀表达式 */ void parser(string& input, vector<string>& marray) { int i, j, k; int length = input.size(); int b = 0, e = 0; while(e < length) { e = input.find_first_of(operat, b); if(e == -1) { marray.push_back(input.substr(b, length - b)); break; } if(b == e) marray.push_back(input.substr(b, 1)); else if(b < e) { marray.push_back(input.substr(b, e-b)); marray.push_back(input.substr(e, 1)); } b = e+1; } } char panduan[2][5] = {"+-*/", "*/*/"}; void Mymove(stack<string>& operatStack, vector<string>& parray, int type) { while(!operatStack.empty() &&(operatStack.top()[0] == panduan[type][0]|| operatStack.top()[0] == panduan[type][1]|| operatStack.top()[0] == panduan[type][2]|| operatStack.top()[0] == panduan[type][3])) { parray.push_back(operatStack.top()); operatStack.pop(); } } /* 中缀表达式marray,转为后缀表达式parray。 */ void inorderTopoxiorder(vector<string>& marray, vector<string>& parray) { stack<string> operatStack; vector<string>::iterator iter; for(iter = marray.begin(); iter != marray.end(); iter ++) { if((*iter)[0] <= '9' && (*iter)[0] >= '0') { parray.push_back(*iter); } else { if((*iter)[0] == '(') operatStack.push(*iter); if((*iter)[0] == ')') { Mymove(operatStack, parray, 0); operatStack.pop(); } if((*iter)[0] == '*' || (*iter)[0] == '/') { Mymove(operatStack, parray, 1); operatStack.push(*iter); } if((*iter)[0] == '+' || (*iter)[0] == '-') { Mymove(operatStack, parray, 0); operatStack.push(*iter); } } } while(!operatStack.empty()) { parray.push_back(operatStack.top()); operatStack.pop(); } } /* 对后缀表达式进行求值,同时返回求值结果 */ int caculate(vector<string>& parray) { vector<string>::iterator iter; stack<int> numStack; for(iter = parray.begin(); iter != parray.end(); iter ++) { if((*iter)[0] <='9' && (*iter)[0] >='0') numStack.push(atoi(iter->c_str())); else { int tmp = 0; int tmp1 = numStack.top(); numStack.pop(); int tmp2 = numStack.top(); numStack.pop(); switch((*iter)[0]) { case '+': tmp = tmp2 +tmp1; break; case '-': tmp = tmp2 -tmp1; break; case '*': tmp = tmp2 *tmp1; break; case '/': if(tmp1 != 0) tmp = tmp2 /tmp1; else { cout << "can't divede zero !!" << endl; abort(); } break; } numStack.push(tmp); } } return numStack.top(); } int main() { while(cin >> input) { cout << input << " = "; parser(input, midarray); inorderTopoxiorder(midarray, parray); cout << caculate(parray) << endl; } return 0; }  

你可能感兴趣的:(四则运算-表达式求值)