你参考一下
```cpp
#include <iostream>
#include <cstdio>
#include <string>
#include <stack>
#include <cmath>
using namespace std;
stack <int> digit;
stack <char> symbol;
int level(char c) {
if (c == '+' || c == '-') return 1;
if (c == '*' || c == '/') return 2;
if (c == '^') return 3;
return 0;
}
void calculation() {
int a = digit.top();
digit.pop();
int b = digit.top();
digit.pop();
char ch = symbol.top();
symbol.pop();
if (ch == '+') digit.push(a + b);
else if (ch == '-') digit.push(b - a);
else if (ch == '*') digit.push(a * b);
else if (ch == '/') digit.push(b / a);
else if (ch == '^') digit.push(pow(b, a));
}
int main()
{
string str;
cin >> str;
int len = str.length();
int x = 0;
bool tag = false;
for (int i = 0; i < len; i ++) {
if (str[i] >= '0' && str[i] <= '9') {
x = x*10 + str[i]-'0';
tag = true;
}
else {
if (tag) {
digit.push(x);
tag = false;
x = 0;
}
if (str[i] == '(') {
symbol.push(str[i]);
continue;
}
if (str[i] == ')') {
while (symbol.top() != '(') calculation();
symbol.pop();
continue;
}
while (!symbol.empty() && level(symbol.top()) >= level(str[i])) calculation();
symbol.push(str[i]);
}
}
if (tag) digit.push(x);
while (!symbol.empty()) calculation();
cout << digit.top() << endl;
return 0;
}
```
by World_Scientology @ 2024-04-22 19:38:06
@[World_Scientology](/user/1281862) 谢谢y已关
by C112345565_ @ 2024-04-22 19:40:00
@[C112345565_](/user/1073331) 小事
by World_Scientology @ 2024-04-22 19:42:23