关于逆波兰式的c++实现

正常的表达式 逆波兰表达式
a+b ---> a,b,+
a+(b-c) ---> a,b,c,-,+
a+(b-c)*d ---> a,b,c,-,d,*,+
a+d*(b-c)--->a,d,b,c,-,*,+
a=1+3 ---> a=1,3 +
 
代码运算如下:
#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;
}

  

原文地址:https://www.cnblogs.com/phpzhou/p/5223867.html