我是小学生 • 3天前
using namespace std; string s; stack c; stack sc;
int level(char i) {
if (i == '^')
return 3;
else if (i == '*' || i == '/')
return 2;
else if (i == '+' || i == '-')
return 1;
else
return 0;
}
void calc() {
int a = c.top();
c.pop();
int b = c.top();
c.pop();
char ch = sc.top();
sc.pop();
if (ch == '+')
c.push(b + a);
else if (ch == '-')
c.push(b - a);
else if (ch == '*')
c.push(b * a);
else if (ch == '/')
c.push(b / a);
else if (ch == '^')
c.push(pow(b, a));
}
int main() {
cin >> s;
s = '(' + s + ')';
int n = s.size();
for (int i = 0; i < n; i++) {
if (s[i] >= '0' && s[i] <= '9') {
int x = 0;
while (s[i] >= '0' && s[i] <= '9') {
x = x * 10 + s[i++] - '0';
}
c.push(x);
}
if (s[i] == '(')
sc.push('(');
else if (s[i] == ')') {
while (sc.top() != '(')
calc();
sc.pop();
} else {
while (!sc.empty() && level(sc.top()) >= level(s[i]))
calc();
sc.push(s[i]);
}
}
cout << c.top() ;
return 0;
}
评论:
请先登录,才能进行评论