题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
#include <iostream>
#include <stack>
using namespace std;
bool isOp(char x){
if (x=='+' || x=='-' || x=='*' || x=='/' || x=='#'){
return true;
}
return false;
}
int priority(char op){
if (op=='+' || op=='-'){
return 1;
} else if (op=='*' || op=='/'){
return 2;
}
return 0;
}
double yunsuan(double x, double y, char op){
switch (op) {
case '+': return x+y;
case '-': return x-y;
case '*': return x*y;
case '/': return x/y;
default: return 0;
}
}
int main() {
string str;
while (getline(cin, str)){
if (str == "0") break;
str.push_back('#');
stack<double> num;
stack<char> op;
string number;
for (int i = 0; i < str.size(); ++i) {
if ('0'<=str[i] && str[i]<='9'){
number.push_back(str[i]);
} else if (str[i]==' ' && !number.empty()){
num.push(stod(number));
number = "";
} else if (isOp(str[i])){
if (str[i]=='#'){
num.push(stod(number));
}
while (!op.empty() && priority(op.top()) >= priority(str[i])){
double y = num.top();
num.pop();
double x = num.top();
num.pop();
char oper = op.top();
op.pop();
double result = yunsuan(x, y, oper);
num.push(result);
}
op.push(str[i]);
}
}
printf("%.2lf\n", num.top());
}
return 0;
}
