初音未来 • 2个月前
#include <bits/stdc++.h>
using namespace std;
stack<int>num;
stack<char>op;
int compare(char x) {
int q = 0;
if (x == '+' || x == '-')
q = 1;
if (x == '*' || x == '/')
q = 2;
if (x == '^')
q = 3;
return q;
}
void deal() {
int a, b;
b = num.top();
num.pop();
a = num.top();
num.pop();
char p = op.top();
op.pop();
if (p == '+')
num.push(a + b);
if (p == '-')
num.push(a - b);
if (p == '*')
num.push(a * b);
if (p == '/')
num.push(a / b);
if (p == '^') {
int f = pow(a, b);
num.push(f);
}
}
void ceal() {
string s;
getline(cin, s);
for (int i = 0; i < s.size(); i++) {
int d = 0;
if (s[i] >= '0' && s[i] <= '9') {
while (s[i] >= '0' && s[i] <= '9') {
int a = s[i] - '0';
d = d * 10 + a;
i++;
}
i--;
num.push(d);
} else if (s[i] == '(' || s[i] == ')') {
if (s[i] == '(')
op.push(s[i]);
else if (s[i] == ')') {
while (op.top() != '(')
deal();
op.pop();
}
} else {
while (op.size() > 0 && compare(op.top()) >= compare(s[i]))
deal();
op.push(s[i]);
}
}
while (!op.empty())
deal();
cout << num.top();
}
int main() {
ceal();
return 0;
}
评论:
请先登录,才能进行评论