题目:求后缀表达式的数值,后缀式存于字符数组exp[]中,以’\0’作为结束符。假设后缀式中的数字都只有,且除法运算为整除运算,如2/3结果为0,3/2结果为1。
思想:遇到数值入栈,遇到运算符,连续两次出栈,将出栈两个元素进行运算,且结果作为新的数值重新存入栈中。直到扫描到’\0’为止,此时栈底元素为表达式的值。
int op(int a,char op,int b) //运算函数,完成a op b的运算
{
if(op=='+') return a+b;
if(op=='-') return a-b;
if(op=='*') return a*b;
if(op=='/')
{
if(b==0) //分母为0则报错
{
printf("ERROR");
return 0;
}
else
return a/b;
}
}
int com(char exp[]) //后缀式计算函数
{
int a,b,c,i; //a,b为操作数,c保存运算结果,i为循环变量
int stack[MAXSIZE];int top = -1;
for(i=0;i!='\0';++i)
{
if(exp[i]>='0' && exp[i]<='9')
stack[++top] = exp[i] - '0'; // 字符型和整型的转换
else
{
op = exp[i];
a = stack[top--];
b = stack[top--];
c = op(a,op,b);
stack[++top] = c;
}
}
return stack[top];
}