⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 postfixeval.h

📁 C++数据结构的例子
💻 H
字号:
#include<iostream>
#include<stack>
#include<string>
#include<ctype.h>
using namespace std;

class postfixEval
{
public:
	postfixEval();
	void setPostfixEval(const string& postfixEval);
	int evaluate();
private:
	string postfixExpression;
	stack<int> operandStack;//运算数栈
	void getOperands(int& left,int& right);//从栈中弹出左右操作数
	int compute(int left,int right,char op)const;
	bool isOperator(char ch)const;
};

postfixEval::postfixEval()
{
	postfixExpression=" ";
}

void postfixEval::setPostfixEval(const string& postfixEval)
{	
	postfixExpression=postfixEval;
}

bool postfixEval::isOperator(char ch)const
{
	char opt[6]={'+','-','*','/','^','%'};
	for(int i=0;i<6;i++)
		if(ch=opt[i])
			return true;
		else
			return false;
}

void postfixEval::getOperands (int& left,int& right)
{
	if(operandStack.empty ())
		throw
			expressionError("postfixEval: Too many operators ");
	right=operandStack.top ();
	operandStack.pop ();
	if(operandStack.empty ())
		throw
			expressionError("postfixEval: Too many operators ");
	left=operandStack.top ();
	operandStack.pop ();
}

int postfixEval::compute(int left,int right,char op)const
{
	int valve;
	switch(op)
	{
	case '+':
		valve=left+right;
		break;
	case '-':
		valve=left-right;
		break;
	case '*':
		valve=left*right;
		break;
	case '%':
		if(right==0)
			throw
				expressionError("postfixEval: Divide by 0 ");
		valve=left % right;
		break;
	case '/':
		if(right==0)
			throw
				expressionError("postfixEval: Divide by 0 ");
		valve=left / right;
		break;
	case'^':
		if(right==0 && left==0)
			throw
				expressionError("postfixEval: 0^0 is undifined ");
		valve=1;
		while(right>0)
		{
			valve *=left;
			right--;
		}
		break;
	}
	return valve;
}

int postfixEval::evaluate ()
{
	int left,right,expValve;
	char ch;
	for(int i;i<postfixExpression.length ();i++)
	{
		ch=postfixExpression[i];
		if(isdigit(ch))
			operandStack.push (ch);
		else 
		{
			if(isOperator(ch))
			{
				getOperands(left,right);
				operandStack.push (compute(left,right,ch));
			}
			else
				cout<<"Error!Improper char!"<<endl;
			}
	}
	expValve=operandStack.top ();
	operandStack.pop ();
	if(!operandStack.empty ())
		throw
			expressionError("postfixEval: Too many operands ");
	return expValve;
}


		





⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -