您的位置:首页 > 其它

计算波兰表达式

2016-03-27 17:02 381 查看
//计算波兰表达式
#include<iostream>
#include<string>

using namespace std;

const int MAX_SIZE = 100;//定义栈的最大容量
typedef struct stack
{
int top;
int data[MAX_SIZE];
}stack;
stack S;
/*
计算波兰表达式
数字入栈,符号计算入栈
*/
void Solution()
{
string s;
cin>>s;
int s_len=s.length();
S.top=0;//初始化
int i=0;//迭代器
int num;//存储中间值
while(i<s_len)
{
if(s[i]>='0'&&s[i]<='9')
S.data[S.top++]=s[i]-'0';
else
{
switch(s[i])
{
case '+':num=S.data[S.top-1]+S.data[S.top-2];S.data[S.top++]=num;break;
case '-':num=S.data[S.top-2]-S.data[S.top-1];S.data[S.top++]=num;break;
case '*':num=S.data[S.top-1]*S.data[S.top-2];S.data[S.top++]=num;break;
case '/':if(S.data[S.top-1]!=0)
{num=S.data[S.top-1]+S.data[S.top-2];S.data[S.top++]=num;break;}
else
cout<<"除数不为0"<<endl;
}
}
i++;
}
cout<<S.data[S.top-1]<<endl;
}
int main()
{
Solution();
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: