题解 | #计算表达式#
计算表达式
https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b
#include <iostream>
#include <stack>
using namespace std;
int Priority(char ch) {
if (ch == '#') {
return 0;
} else if (ch == '$') {
return 1;
} else if (ch == '+' || ch == '-') {
return 2;
} else {
return 3;
}
}
double opeNum(double a, double b, char ch) {
if (ch == '+') {
return a + b;
} else if (ch == '-') {
return a - b;
} else if (ch == '*') {
return a * b;
} else {
return a / b;
}
}
int main() {
string str;
while (cin >> str) {
stack<double> num;
stack<char> ope;
ope.push('#');
str += '$';
int i=0;
while(i<str.size()){
if(isdigit(str[i])){
double number = 0;
while (isdigit(str[i])) {
number = number * 10 + str[i] - '0';
i++;
}
num.push(number);
} else {
char ch=ope.top();
if (Priority(str[i]) > Priority(ch)) {
ope.push(str[i]);
i++;
} else {
double b = num.top();
num.pop();
double a = num.top();
num.pop();
num.push(opeNum(a, b, ch));
ope.pop();
}
}
}
cout<<num.top()<<endl;
}
}


神州信息成长空间 29人发布