题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
#include <iostream> #include<stack> //参考答案解法,磕磕绊绊,还不熟练 using namespace std; int priority(char c) { if (c == '#') { //运算符栈 return 0; } else if (c == '$') { return 1; } else if (c == '+' || c == '-') { return 2; } else { return 3; } } double getNumber(string str, int& index) { //获得索引 double number = 0; while (isdigit(str[index])) { //判断是否是数字 number = number * 10 + str[index] - '0'; index++; } return number; } double Calculate(char operSign, double operNum1, double operNum2) { double resultNum = 0; if (operSign == '+') { resultNum = operNum1 + operNum2; } else if (operSign == '-') { resultNum = operNum1 - operNum2; } else if (operSign == '*') { resultNum = operNum1 * operNum2; } else if (operSign == '/') { resultNum = operNum1 / operNum2; } return resultNum; } int main() { string str; while (getline(cin, str)) { if (str == "0") break; //双引号,0就退出 stack<double> data; stack<char> oper; int index = 0; str += '$'; oper.push('#'); while (index < str.size()) { if (isdigit(str[index])) { data.push(getNumber(str, index)); } else if (str[index] == ' ') { index++; } else { if (priority(oper.top()) < priority(str[index])) { oper.push(str[index]); index++; } else { double x = data.top(); data.pop(); double y = data.top(); data.pop(); data.push(Calculate(oper.top(), y, x)); oper.pop(); } } } printf("%.2f\n", data.top()); } return 0; }