算术表达式求值

2025-04-17 15:23:20
推荐回答(2个)
回答1:

#include
#include//STL
#define MaxSize 200
using namespace std;
bool judge(char a, char b)//判断进栈的运算符级别是否高于等于栈顶,是返回true,否返回false
{
if(a=='+'||a=='-')
if(b=='*'||b=='/')
return false;
return true;
}
int cal(int b1,int b2, char c)//判断运算符后计算
{
if(c=='+')
return b1+b2;
if(c=='-')
return b1-b2;
if(c=='*')
return b1*b2;
if(c=='/')
return b1/b2;
}
int main()//主函数
{
bool flag;//标志
stack num;//整形栈,用来存放操作数
stack op;//字符栈,用来存放运算符
char a[MaxSize],c;//字符串a用来存放表达式,c存放单个字符
int b[2];//存放出栈的两个操作数
cin >> a;//读入
for(int i=0;a[i]!='\0';i++) //循环
{
flag=true;
c='\0';
if(a[i]>='0'&&a[i]<='9')//判断字符串中的元素属于操作数还是运算符
num.push(a[i]-'0');//进栈
else
{
if(op.empty())//判断运算符是否是初次进栈
{
op.push(a[i]);
flag=false;
}
if(judge(a[i],op.top())&&flag)//运算符进栈
op.push(a[i]);
if(flag&&!judge(a[i],op.top()))//如果进栈的运算符级别低于栈顶,则出栈
{
c=op.top();
op.pop();
b[1]=num.top();
num.pop();
b[0]=num.top();
num.pop();
i--;
}
if(c!='\0')
{
num.push(cal(b[0],b[1],c));//计算
}

}
}
while(!op.empty())//运算符的栈不为空,则出栈进行计算
{
c=op.top();
op.pop();
b[1]=num.top();
num.pop();
b[0]=num.top();
num.pop();
num.push(cal(b[0],b[1],c));
}
if(num.size()==1) //输出运算结果
cout << num.top() << endl;
return 0;
}

回答2:

23