四则运算
#include <iostream> #include <string> #include <stack> using namespace std; bool cmpPriority(char top, char cur) //top的优先级高于cur时,返回ture,此处不将当前值与‘(’对比 { if ((top == '+' || top == '-') && (cur == '+' || cur == '-')) return true; if ((top == '*' || top == '/') && (cur == '+' || cur == '-' || cur == '*' || cur == '/')) return true; return false; } void preProcess(string &str) { for (int i = 0; i < str.size(); i++) { if (str[i] == '{' || str[i] == '[') str[i] = '('; if (str[i] == '}' || str[i] == ']') str[i] = ')'; if (str[i] == '-') { if (i == 0 || str[i - 1] == '(') str.insert(i, 1, '0'); } } } void doCal(stack<int>& numStack, stack<char>& operStack) { int b = numStack.top(); //注意运算顺序,a+b压入栈后,b在上 numStack.pop(); int a = numStack.top(); numStack.pop(); char op = operStack.top(); operStack.pop(); switch (op) { case '+': a += b; break; case '-': a -= b; break; case '*': a *= b; break; case '/': a /= b; break; } numStack.push(a); } int main() { string s; while (getline(cin, s)) { preProcess(s); stack<int> numStack; stack<char> operSatck; operSatck.push('('); //确保栈顶有值 s.push_back(')'); for (int i = 0; i < s.size(); i++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') operSatck.push('('); else if (s[i] == ')' || s[i] == ']' || s[i] == '}') { while (operSatck.top() != '(') doCal(numStack, operSatck); operSatck.pop(); } else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') // { while (cmpPriority(operSatck.top(), s[i])) doCal(numStack, operSatck); operSatck.push(s[i]); } else if (isdigit(s[i])) { int j = i; while (i < s.size() && isdigit(s[i])) { i++; } string temp = s.substr(j, i - j); numStack.push(stoi(temp)); i--; } } cout << numStack.top() << endl; } return 0; }
posted on 2020-09-01 11:26 waterrzhang 阅读(123) 评论(0) 编辑 收藏 举报