标签:
#include "iostream"
#include "string"
#include "stack"
using namespace std;
int main()
{
string str;
stack<int> sk;
int s = 0, l = 0, r = 0;
cout << "请输入逆波兰公式:" << endl;
while (cin>>str)
{
if (str[0] == ‘#‘)
{
break;
}
//如果第一个是0-9数字则转换为数字压栈
else if (isdigit(str[0]))
{
sk.push(atoi(str.c_str()));
}
else
{
l = sk.top();
sk.pop();
r = sk.top();
sk.pop();
switch (str[0])
{
case ‘+‘:
s = r + l;
break;
case ‘-‘:
s = r - l;
break;
case ‘*‘:
s = r * l;
break;
case ‘/‘:
s = r / l;
break;
}
//把计算的结果再次压栈
sk.push(s);
}
}
cout << "结果为:" << s << endl;
system("pause");
return 0;
}
标签:
原文地址:http://www.cnblogs.com/phpzhou/p/5223867.html