题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
#include <iostream> #include <stack> #include <map> using namespace std; double func(double x, double y, char c) { if (c == '+') return x + y; else if (c == '-') return x - y; else if (c == '*') return x * y; else if (c == '/') return x / y; return -1; } int main() { map<char, int> m; m['+'] = 1, m['-'] = 1, m['*'] = 2, m['/'] = 2; string str; while (getline(cin, str)) { if (str == "0") break; stack<double> nums; stack<char> op; for (int i = 0; i < str.size(); i++) { if (isdigit(str[i])) { int j = i; while (j < str.size() && isdigit(str[j])) j++; //i~j-1是一个数 int t = 0; for (int k = i; k < j; k++) t = 10 * t + str[k] - '0'; nums.push(t); i = j - 1; //i++以后指向下一个字符 } else if (str[i] != ' ') { //读到了运算符 while (!op.empty() && m[op.top()] >= m[str[i]]) { double y = nums.top(); //右操作数 nums.pop(); double x = nums.top(); //左操作数 nums.pop(); char c = op.top(); op.pop(); double res = func(x, y, c); nums.push(res); } op.push(str[i]); } } while (!op.empty()) { double y = nums.top(); //右操作数 nums.pop(); double x = nums.top(); //左操作数 nums.pop(); char c = op.top(); op.pop(); double res = func(x, y, c); nums.push(res); } printf("%.2lf\n",nums.top()); nums.pop(); } return 0; }