#include <iostream> #include <cstdio> #include <stack> #include <string> #include <map> using namespace std; double calculate(char opera, double leftNum, double rightNum); map<char, int> priority = { {'$', 0}, {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2} }; /** * 计算表达式--上海交通大学 * @return */ int main() { string str; cin >> str; str += "#"; stack<char> operaStack; stack<double> numStack; string num = ""; for (int i = 0; i < str.size(); ++i) { char cur = str[i]; if (cur == '#') { if (num != "") { numStack.push(stod(num)); num = ""; } while (!operaStack.empty()) { char opera = operaStack.top(); operaStack.pop(); double rightNum = numStack.top(); numStack.pop(); double leftNum = numStack.top(); numStack.pop(); numStack.push(calculate(opera, leftNum, rightNum)); } } else if ('0' <= cur && cur <= '9') { num += cur; } else { if (num != "") { numStack.push(stod(num)); num = ""; } while (!operaStack.empty() && priority[operaStack.top()] >= priority[cur]) { char opera = operaStack.top(); operaStack.pop(); double rightNum = numStack.top(); numStack.pop(); double leftNum = numStack.top(); numStack.pop(); numStack.push(calculate(opera, leftNum, rightNum)); } operaStack.push(cur); } } cout << numStack.top() << endl; return 0; } double calculate(char opera, double leftNum, double rightNum) { double res = 0; switch (opera) { case '+': res = leftNum + rightNum; break; case '-': res = leftNum - rightNum; break; case '*': res = leftNum * rightNum; break; case '/': res = leftNum / rightNum; break; default: break; } return res; }