逆波兰实现计算器

#include <iostream>
#include <stack>
#include <string>

using namespace std;

bool isopretor(char ch)
{
	switch(ch)
	{
	case '+' :
	case '-':
	case '*':
	case '/':
	case '%':
		return 1;
	default:
		return -1;
	}
}

int priority(char ch)
{
	switch(ch)
	{
	case '*':
	case '/':
	case '%':
		return 2;
	case '(':
		return 0;
	case '+':
	case '-':
		return 1;
	case '#':
		return -1;
	default:
		return -1;
	}
}

void postfix(string &pre,char post[],int &len)
{
	int i=0,j=0;
	stack<char>mystack;
	mystack.push('#');
	while (pre[i]!='#')
	{
		if (pre[i]=='(')
		{
			mystack.push(pre[i]);
		}else if ( (pre[i]>='0' && pre[i]<='9')||pre[i]== '.')
		{
			post[j++]=pre[i];
		}
		else if (pre[i]==')')
		{
			while(mystack.top()!='(')
			{
				post[j++]=mystack.top();
				mystack.pop();
			}
			mystack.pop();
		}
		else if (isopretor(pre[i]))
		{
			post[j++]=' ';
			while(priority(pre[i])<=priority(mystack.top()))
			{
				post[j++]=mystack.top();
				mystack.pop();
			}
			mystack.push(pre[i]);
		}
		i++;
	}
	while (mystack.top()!='#')//模板类stack top方法报错当没有元素时
	{
		post[j++]=mystack.top();
		mystack.pop();
	}
	post[j]='#';
	len=j;
}
//把字符串数据转为数字存下来
double read_num(char *post,int &i)
{
	double sum=0;
	while (post[i]>='0'&&post[i]<='9')
	{
		sum=sum*10+post[i]-'0';
		i++;
	}
	int k=0;
	if (post[i]=='.')
	{
		i++;
		while (post[i]>='0'&&post[i]<='9')
		{
			sum=sum*10+post[i]-'0';
			i++;k++;

		}
	}
	if (k!=0)
	{
		sum/=pow(10.0,k);
	}
	return sum;
}
//计算逆波兰的值
double postValue(char *post)
{
	stack<double>mystack;
	double x1,x2;
	int i=0;
	while (post[i]!='#')
	{
		if (post[i]>='0'&&post[i]<='9')
		{
			mystack.push(read_num(post,i));
		}
		else if (post[i]==' ')
		{
			i++;
		}
		else if (post[i]=='+')
		{
			x2=mystack.top();
			mystack.pop();
			x1=mystack.top();
			mystack.pop();
			mystack.push(x1+x2);
			i++;
		}
		else if (post[i]=='-')
		{
			x2=mystack.top();
			mystack.pop();
			x1=mystack.top();
			mystack.pop();
			mystack.push(x1-x2);
			i++;
		}
		else if (post[i]=='*')
		{
			x2=mystack.top();
			mystack.pop();
			x1=mystack.top();
			mystack.pop();
			mystack.push(x1*x2);
			i++;
		}
		else if (post[i]=='/')
		{
			x2=mystack.top();
			mystack.pop();
			x1=mystack.top();
			mystack.pop();
			mystack.push(x1/x2);
			i++;
		}
		else if (post[i]=='%')
		{
			x2=mystack.top();
			mystack.pop();
			x1=mystack.top();
			mystack.pop();
			mystack.push((int)x1%(int)x2);
			i++;
		}
	}
	return mystack.top();
}
int main()
{
	string pre="(2+4)*5+(5-2)/2#";
	char post[100];
	int len=0;
	postfix(pre,post,len);//转成逆波兰
	for (int i=0;i<len;i++)
	{
		cout<<post[i];
	}	
	cout<<endl;
	cout<<postValue(post)<<endl;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值