题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
#include <iostream> #include <algorithm> #include <stack> #include <string> #include <cstdio> #include <map> using namespace std; //KY129 int main() { char buf[400]; //用map来存储运算符的优先级 map<char, int> priority = { {'$', 0}, {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2} }; while (fgets(buf, 400, stdin) != NULL) { string expr = buf; //转换成C++风格的字符串,expression expr.pop_back(); //弹出最后的换行符 if (expr == "0") { break; } expr.push_back('$'); //加上结尾 string num; //用来收集单独的数字 1 3 -> 13 stack<double> numStack; stack<char> operStack; for (int i = 0; i < expr.size(); i++) { if (expr[i] >= '0' && expr[i] <= '9') { //如果是数字,则追加到num后面 num.push_back(expr[i]); } else if (expr[i] == ' ') { //直到读取到空格 if (num != "") { //如果num有值,则放到操作数里 numStack.push(stod(num)); //stod(string s) 把s转换成double类型 num = ""; } } else { if (expr[i] == '$') { if (num != "") { numStack.push(stod(num)); //stod(string s) 把s转换成double类型 num = ""; } } while (!operStack.empty() && priority[operStack.top()] >= priority[expr[i]]) { double num1 = numStack.top(); numStack.pop(); double num2 = numStack.top(); numStack.pop(); char top = operStack.top(); operStack.pop(); switch (top) { case '+': numStack.push(num2 + num1); break; case '-': numStack.push(num2 - num1); break; case '*': numStack.push(num2 * num1); break; case '/': numStack.push(num2 / num1); break; } } operStack.push(expr[i]); } } //输出最后的字符 printf("%.2lf\n", numStack.top()); numStack.pop(); } }