输入只含数字和运算符的后缀表达式,求其值。
#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;
}