题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
#include <iostream>
#include<stack>
#include<string>
#include<map>
using namespace std;
int main() {
string str;
string str_s;
int tag = 0;
stack<double> Mystack;
stack<char> Stack_1;
map<char, int> Map;
Map['+'] = 1;
Map['-'] = 1;
Map['*'] = 2;
Map['/'] = 2;
while (getline(cin, str)) {
if (str == "0") {
break;
}
str.insert(0, " ");
str.push_back(' ');
for (int i = 1; i < str.size(); ++i) {
if (str[i] == ' ' && str[i - 1] >= '0' && str[i - 1] <= '9') {
double x = stod(str.substr(tag, i - tag + 1));
Mystack.push(x);
}
else if (str[i] >= '0' && str[i] <= '9' && str[i - 1] == ' ') {
tag = i;
}
if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/') {
if (Stack_1.empty()) {
Stack_1.push(str[i]);
}
else {
if (Map[Stack_1.top()] >= Map[str[i]]) {
while (Stack_1.empty() == false && Map[Stack_1.top()] >= Map[str[i]]) {
double x1 = Mystack.top();
Mystack.pop();
double x2 = Mystack.top();
Mystack.pop();
if (Stack_1.top() == '+') {
Mystack.push(x1 + x2);
}
else if (Stack_1.top() == '-') {
Mystack.push(x2 - x1);
}
else if (Stack_1.top() == '*') {
Mystack.push(x2 * x1);
}
else if (Stack_1.top() == '/') {
Mystack.push((double)x2 / x1);
}
Stack_1.pop();
}
Stack_1.push(str[i]);
}
else {
Stack_1.push(str[i]);
}
}
}
}
while (!Stack_1.empty()) {
double x1 = Mystack.top();
Mystack.pop();
double x2 = Mystack.top();
Mystack.pop();
if (Stack_1.top() == '+') {
Mystack.push(x1 + x2);
}
else if (Stack_1.top() == '-') {
Mystack.push(x2 - x1);
}
else if (Stack_1.top() == '*') {
Mystack.push(x2 * x1);
}
else if (Stack_1.top() == '/') {
Mystack.push((double)x2 / x1);
}
Stack_1.pop();
}
printf("%.2lf\n", Mystack.top());
Mystack.pop();
}
}
// 64 位输出请用 printf("%lld")
拼多多集团-PDD成长空间 966人发布