#include <bits/stdc++.h>
using namespace std;
string a;
int shuzi(int l, int r)
{
int sum = 0;
for (int i = l; i <= r; i++)
{
sum = sum * 10 + a[i] - '0';
}
return sum;
}
int cal(int l, int r)
{
int cnt = 0;
int pos1 = -1, pos2 = -1, pos3 = -1;
for (int i = l; i <= r; i++)
{
if (a[i] == '(')
cnt++;
if (a[i] == ')')
cnt--;
if (cnt <= 0)
{ // 括号外或者没括号,定位最右边运算符位置(同优先级下,右边慢算)
if (a[i] == '+' || a[i] == '-')
pos1 = i;
if (a[i] == '*' || a[i] == '/')
pos2 = i;
if (a[i] == '^')
pos3 = i;
}
}
if (pos1 == -1 && pos2 == -1 && pos3 == -1)
{ // 括号内
if (cnt > 0 && a[l] == '(')
return cal(l + 1, r);
if (cnt < 0 && a[r] == ')')
return cal(l, r - 1);
if (cnt == 0 && a[l] == '(')
return cal(l + 1, r - 1); // 去括号
return shuzi(l, r);
}
else if (pos1 != -1)
{ // 把其他看作整体(即数学中的先算),然后把整体相加减
if (a[pos1] == '+')
return cal(l, pos1 - 1) + cal(pos1 + 1, r);
else
return cal(l, pos1 - 1) - cal(pos1 + 1, r);
}
else if (pos2 != -1)
{
if (a[pos2] == '*')
return cal(l, pos2 - 1) * cal(pos2 + 1, r);
else
return cal(l, pos2 - 1) / cal(pos2 + 1, r);
}
else
{
return pow(cal(l, pos3 - 1), cal(pos3 + 1, r));
}
}
int main()
{
cin >> a;
int len = a.size();
cout << cal(0, len - 1);
}
表达式求值
最新推荐文章于 2025-12-15 22:32:00 发布
2112





