题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
#include <iostream> #include <cstring> #include <stack> #include <map> using namespace std; map<char, int> level = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}}; double cpt(double a, double b, char c) { if( c == '+') return a + b; else if( c == '-') return a - b; else if( c == '*') return a * b; return a / b; } void computer(string s) { stack<double> num; stack<char> ops; for(int i = 0; i < s.size(); i ++) { char c = s[i]; if(c == ' ') continue; if(c >='0' && c <= '9') { double t = 0; while(i < s.size() && s[i] >='0' && s[i] <= '9') { t = t * 10 + s[i] - '0'; i ++; } i = i - 1; num.push(t); // cout << num.top() << " " << i << endl; } else if(ops.empty() || level[c] > level[ops.top()]) ops.push(c); else { while(ops.size() && level[c] <= level[ops.top()]) { double b = num.top(); num.pop(); double a = num.top(); num.pop(); char op = ops.top(); ops.pop(); num.push(cpt(a, b, op)); // cout << num.top() << " " << endl; } ops.push(c); } } while(ops.size()) { double b = num.top(); num.pop(); double a = num.top(); num.pop(); char op = ops.top(); ops.pop(); num.push(cpt(a, b, op)); // cout << num.top() << " " << endl; } double ret = num.top(); printf("%.2lf\n", ret); } int main() { string s; while (getline(cin, s) && s != "0") { // 注意 while 处理多个 case computer(s); } return 0; } // 64 位输出请用 printf("%lld")