#include<iostream>
#include <unordered_map>
using namespace std;
const int N=10010;
char op[N];int num[N];
int idx1=-1,idx2=-1;//模拟栈
void cal()
{
int b=num[idx2--];
int a=num[idx2--];
//注意a,b顺序
char c=op[idx1--];
int x=0;
if(c=='+')x=a+b;
else if(c=='-')x=a-b;
else if(c=='*')x=a*b;
else if(c=='/')x=a/b;
num[++idx2]=x;//压入x
}
bool isnum(char a)
{
if(a>='0'&&a<='9')return true;
return false;
}
int main()
{
string s;cin>>s;
unordered_map<char,int>pr={{'+',1},{'-',1},{'*',2},{'/',2}};
//优先级
for(int i=0;i<s.size();i++)
{
if(isnum(s[i]))
{
int j=i,x=0;
while(j<s.size()&&isnum(s[j]))
{
x=x*10+s[j]-'0';//不可能只是个数
j++;
}
num[++idx2]=x;
i=j-1; //i要循环后要++
}
else if(s[i]=='(')op[++idx1]='(';//直接入栈
else if(s[i]==')')
{
while(s.size()&&op[idx1]!='(')cal();//遇到'('是才计算,把'('删了
idx1--;
}
else
{
while(s.size()&&op[idx1]!='('&&pr[op[idx1]]>=pr[s[i]])
//+-*/除非遇到'('才或优先级大于栈顶停止运算
cal();
op[++idx1]=s[i];
}
}
while(idx1+1) cal();
cout<<num[idx2]<<endl;
return 0 ;
}
标签:int,else,char,num,求值,idx2,idx1,表达式
From: https://blog.csdn.net/2301_80035407/article/details/136814522