基于栈的应用之计算后缀表达式

算法:1、当输入操作数时,计算器便将其入栈
           2、当显示操作符时,计算器将其用于栈顶的两个操作数,使操作数出栈,按照操作符的指示执行计算。
           3、使步骤2的操作结果入栈。
           4、读取下一个字符依次重复执行1 2 3 的步骤。当达到后缀表达式末尾时终止。
算法终止时,表达式的值位于栈顶。

用#作为不是同一个操作单元的分隔符(操作数,操作符)
本算法的前提要求: *字符串是语法正确的后缀表达式  *不存在一元操作符   *不存在求幂操作符

 

#include<iostream>
#include<stack>
#include<cmath>
#include<string>
using namespace std;
bool isIndent(char ch);
bool isOperand(char ch);
bool isDicim(char ch);
bool isOperator(char ch);
double computing(double n1,double n2,char ch);
double post_cal(const string &str);

int main()
{
	cout<<"enter a right postfix expression :";
	string st;
	getline(cin,st);
	cout<<"now begin computing !"<<endl;
	cout<<"the result is "<<post_cal(st)<<endl;
	return 0;
}

bool isIndent(char ch)
{
	return ch==' ';
}
bool isOperand(char ch)
{
	return (ch>='0'&&ch<='9');
}
bool isDicim(char ch)
{
	return ch=='.';
}
bool isOperator(char ch)
{
	return (ch=='+'||ch=='-'||ch=='/'||ch=='*');
}
double computing(double n1,double n2,char ch)
{
	double result;
	switch(ch)
	{
		case '+':result=n1+n2;break;
		case '-':result=n1-n2;break;
		case '/':result=n1/n2;break;
		case '*':result=n1*n2;break;
	}
	return result;
}
double post_cal(const string &str)
{
	stack<double> operands;
	int index=str.size();
	int i=0;
	char ch=str[i];
	double inte=0;
	double dicim=0;
	while(i<index)
	{
		if(!isIndent(ch))
		{
			if(isOperand(ch))
			{
				while(isOperand(ch))
				{
					inte=inte*10+(ch-'0');
					i++;
					ch=str[i];
				}
		          	if(isDicim(ch))
		          	{
		         		i++;
		           		ch=str[i];
		            		int s=0;
		           		while(!isIndent(ch))
		          		{
		              			s++;
		             			dicim=dicim+pow(0.1,i)*(ch-'0');
		              			i++;
		         			ch=str[i];
		          		}
		       	   	}
				i--;
				operands.push(inte+dicim);
		    	}	
			else	if(isOperator(ch))
			{
				double op1=operands.top();
				operands.pop();
				double op2=operands.top();
				operands.pop();
				operands.push(computing(op2,op1,ch));
				cout<<op1<<"        "<<op2<<endl;
			}
		}
		inte=dicim=0;
		i++;
		ch=str[i];
	}
	return operands.top();
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值