题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
//本题其实是典型的使用栈来计算后缀表达式,照着后缀表达式的计算方式即可
//这里我用map来存储运算符的优先级
//本题还有一个很重要的问题就是一个数字可能有多位数要记得判断
#include <iostream>
#include<stack>
#include<string>
#include <map>
#include<cctype>
using namespace std;
double calculate(double a, double b, char op) {
double n1 = double(a);
double n2 = double(b);
switch (op) {
case'+':
return n1 + n2;
break;
case '-':
return n1 - n2;
break;
case '*':
return n1 * n2;
break;
case '/':
return n1 / n2;
break;
}
return 0;
}
//一个数字可能有多位数所以需要往后查看
double GetNumber(string str, int& index) {
double number = 0;
//判断后面的书符是否是数字
while (str[index] >= '0' && str[index] <= '9') {
number = number * 10 + str[index] - '0';
index++;
}
return number;
}
int main() {
string str;
map<char, int> m;//存储运算符优先级
m['+'] = 1;
m['-'] = 1;
m['*'] = 2;
m['/'] = 2;
while (getline(cin, str)) {
if (str == "0") break;
stack<double> s1;
stack<char> op;
for (int i = 0; i < str.size(); i++) {
if (str[i] >= '0' && str[i] <= '9') {
s1.push(GetNumber(str, i));
} else {
if (str[i] == ' ')
continue;
else {
if (op.empty() || m[op.top()] < m[str[i]]) {
op.push(str[i]);
} else {
while (m[op.top()] >= m[str[i]]) {
//将运算符栈内所有大于当前遍历运算符的运算全部运算
double b = s1.top();
char ch = op.top();
op.pop();
s1.pop();
double a = s1.top();
s1.pop();
s1.push(calculate(a, b, ch));
if (op.empty()) break;
}
op.push(str[i]);
}
}
}
}
while (!s1.empty()) {
double b = s1.top();
char ch = op.top();
op.pop();
s1.pop();
double a = s1.top();
s1.pop();
s1.push(calculate(a, b, ch));
if (s1.size() == 1) {
printf("%0.2f\n", calculate(a, b, ch));
break;
}
}
}
}
查看8道真题和解析