题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
//高优先级压栈,低或相等优先级弹栈计算即可
#include "stdio.h"
#include "string"
#include "stack"
#include "map"
using namespace std;
stack<char> operStack;
stack<double> numStack;
string str;
void calculate(){
char operation = operStack.top();operStack.pop();
double a = numStack.top();numStack.pop();
double b = numStack.top();numStack.pop();
double num;
switch (operation) {
case '+':
num=a+b;
numStack.push(num);break;
case '-':
num=b-a;
numStack.push(num);break;
case '*':
num=a*b;
numStack.push(num);break;
case '/':
num=b/a;
numStack.push(num);break;
default:
break;
}
}
int main(){
char buf[300];
map<char,int> priority = {
{'$',0},
{'+',1},{'-',1},
{'*',2},{'/',2}
};
while (fgets(buf,300,stdin)!=NULL){
str=buf;
str.pop_back();
if(str=="0")
break;
str.push_back('$');
string num;
for (int i = 0; i < str.size(); ++i) {
if(str[i]>='0' && str[i]<='9'){ //是数字
num.push_back(str[i]);
} else if(str[i] == ' '){//为空格时
if(!num.empty()){ //若数字不为空,则压入栈中
numStack.push(stod(num));
num.clear();
}
} else{ //此为+ - * /情况
if(str[i]=='$'){
if(!num.empty()){ //若数字不为空,则压入栈中
numStack.push(stod(num));
num.clear();
}
}
while (!operStack.empty() && priority[operStack.top()] >= priority[str[i]]){//要弹栈
calculate();
}
operStack.push(str[i]);
}
}
printf("%.2lf\n",numStack.top());
numStack.pop();
str.clear();
}
}