您的位置:首页 > 其它

后缀表达式求值

2013-04-18 09:37 106 查看
输入只含数字和运算符的后缀表达式,求其值。

#include<iostream>
#include<stack>
#include<ctype.h>
#include<math.h>
#include<string>
using namespace std;
bool issymbol(unsigned char c)
{
if ((c== '+')||(c== '-')||(c== '*')||(c== '/'))
return true;
return false;

}
void main()
{
stack<int> s1;
unsigned char ch,che;
int a,b;
int sum=0;
ch=cin.get();
while(ch!='#')
{
if(ch==' '||ch=='\n')
{
ch=cin.get();
}
else if(issymbol(ch))
{
if(!s1.empty())
{
a=s1.top();
s1.pop();
}
if(!s1.empty())
{
b=s1.top();
s1.pop();
}
if(ch=='+')
{
s1.push(a+b);
}
else if(ch=='-')
{
s1.push(b-a);
}
else if(ch=='*')
{
s1.push(a*b);
}
else
{
s1.push(b/a);
}
ch=cin.get();

}
else if(isdigit(ch))
{
sum=ch-48;
ch=cin.get();
while(isdigit(ch))
{
sum=sum*10+ch-48;
ch=cin.get();
}
s1.push(sum);

}
else
ch=cin.get();

}
if(!s1.empty())
cout<<s1.top()<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: