编写一个函数,求后缀式的数值。
其实,将数值压入栈,当遇到运算符时,让两个数值连续出栈,即可实现后缀表达式的运算
#include<iostream>
#define maxSize 50
using namespace std;
int op(int a,char Op,int b)
{
if(Op=='+') return a+b;
if(Op=='-') return a-b;
if(Op=='*') return a*b;
if(Op=='/')
{
if(b==0)
{
cout<<"ERROR"<<endl;
return 0;
}else
return a/b;
}
}
int com(char exp[])
{
int i,a,b,c;
int stack[maxSize];int top=-1;
char Op;
for(i=0;exp[i]!='#';++i)
{
if(exp[i]>='0' && exp[i]<='9')
stack[++top]=exp[i]-'0';
else
{
Op=exp[i];
b=stack[top--];
a=stack[top--];
c=op(a,Op,b);
stack[++top]=c;
}
}
return stack[top];
}
int main()
{
char a[maxSize];
cout<<"请输入后缀表达式,以#结束: ";
int i=0;
while(cin>>a[i],a[i]!='#')
{
i++;
}
for(int j=0;j<i;j++)
cout<<a[j];
cout<<endl;
cout<<com(a)<<endl;
return 0;
}
posted on 2012-08-22 10:26
yyj 阅读(104)
评论(0) 编辑 收藏 引用