后缀表达式求值

注意:前两种方法只能算一位数的运算,第三种方法可以两位数以上的运算

这有两种方法,中心思想是一样的只不过定义的字符类型不一样

第一种方法用的是 字符指针类型 (我认为这种方法更好)

#include<iostream>
#include<stack>
using namespace std;

double cal(char* A)
{
	stack<char> s;
	char ch = *A;
	int res = 0;
	while (ch != '#')
	{
		if (ch >= '0' && ch <= '9')
			s.push(ch - '0');
		else if(ch != ' ')
		{
			int num1 = s.top(); s.pop();
			int num2 = s.top();	s.pop();

			if (ch == '+')	res = num1 + num2;
			else if (ch == '-')	res = num2 - num1;
			else if (ch == '*')	res = num1 * num2;
			else if (ch == '/')	res = num1 / num2;
			s.push(res);
		}	
		ch = *A++;
	}
	return s.top();
	s.pop();
}

int main()
{
	char* A = (char*)"3 4 + 5 * 6 - #";
	printf("%.2lf \n", cal(A));
}

第二种用的是 字符数组类型 

#include<iostream>
#include<stack>
using namespace std;


double cal(char ch[])
{
	stack<int> s;
	int i = 0;
	int res = 0;
	while (ch[i] != '\0')
	{

		if (ch[i] >= '0' && ch[i] <= '9') s.push(ch[i] - '0');
		else if(ch[i] != ' ')
		{
			int num1 = s.top(); s.pop();
			int num2 = s.top();	s.pop();

			if (ch[i] == '+')	res = num1 + num2;
			else if (ch[i] == '-')	res = num2 - num1;
			else if (ch[i] == '*')	res = num1 * num2;
			else if (ch[i] == '/')	res = num1 / num2;
			s.push(res);
		}	
		i++;
	}
	return s.top();
	s.pop();
}

int main()
{
	char A[999] = "3 4 + 5 * 6 -";

	printf("%.2lf \n", cal(A));
}

第三种方法会用到

①  使用stringstream类 和 getline方法 使得将字符串以空格划分(java里面直接用split函数不要太方便,C++只能自己写一个split函数,这里为了方便,使用getline方法)。 头文件#include<stack>

②  运用正则表达式,只要不是运算符(也就是是数字)我们就将他入栈。\\d+表示从多位数,使用regex库里面的regex_match函数。 

③  运用atoi函数(整型)atof(浮点型)atol(长整型),将string转为double,atof()函数需要多少const char* 类型,但我们的是string类型,所以我们要多加个string.c_str()函数。

 

#include<iostream>
#include<stack>
#include<regex>
#include<sstream>
#include<cstdlib>
using namespace std;


double cal(string a)
{
	stringstream input(a);
	string str, ch;
	stack<double> s; //用STL库里面的栈,这样方便 
	while (getline(input, str, ' ')) //三个参数分别是 输入流,字符串常引用,分割符 
	{
		ch = str;
		double res = 0;
		while (ch != "\0")
		{

			if (regex_match(ch, regex("\\d+")))//正则表达式,当传入字符串是多位数就入栈 
			{
				double a = atoi(ch.c_str());
				s.push(a);
			}
			else
			{
				double num1 = s.top(); s.pop();
				double num2 = s.top();	s.pop();

				if (ch == "+")	res = num1 + num2;
				else if (ch == "-")	res = num2 - num1;
				else if (ch == "*")	res = num1 * num2;
				else if (ch == "/")	res = num1 / num2;
				s.push(res);
			}
			break;
		}
	}
	return s.top();
	s.pop();
}

int main()
{
	string s = "300 4 + 5 * 6 -"; //多位数运算 
	printf("%.2lf \n", cal(s));
}

如有错误请斧正,谢谢!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值