题解 | #计算表达式#
计算表达式
https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
bool isdigit(char x){
if(x>='0' && x<='9') return true;
else return false;
}
double getnum(string x,int &index){
double k=0;
while(isdigit(x[index])){
k=k*10+x[index]-'0';
index++;
}
return k;
}
int priority(char x){
if(x=='+'||x=='-') return 3;
else if(x=='*'||x=='/') return 4;
else if(x=='$') return 2;
else return 1;
}
int main() {
string exp;
while(cin>>exp){
stack<char> oper;
stack<double> operand;
oper.push('#');
exp+='$';
int i=0;
while(i<exp.length()){
if(isdigit(exp[i])) {
double n=getnum(exp,i);
operand.push(n);
}
else if( priority(exp[i])>priority(oper.top())) {
oper.push(exp[i]);
i++;
}
else {
double o2=operand.top();
operand.pop();
double o1=operand.top();
operand.pop();
char op=oper.top();
double r;
if(op=='+') r=o1+o2;
else if(op=='-') r=o1-o2;
else if(op=='*') r=o1*o2;
else if(op=='/') r=o1/o2;
oper.pop();
operand.push(r);
}
}
cout<<operand.top()<<endl;
}
}


基恩士成长空间 455人发布