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

📄 infix.h

📁 利用栈求解算术表达式的值
💻 H
字号:
#include"Priority.h"

//中缀类Infix的声明,类Infix封装着中缀表达式的运算功能
class Infix
{
private:
	int a,b;
	char Theta;
	LinkStack<int> OPND;
	LinkStack<char> OPTR;


public:
	Infix();                              //中缀表达式的类构造函数
	void InExpress(string &exp);          //中缀表达式的计算函数
    int Operate(int a,char theta,int b);   //两个数之间的四则运算函数
};




//类Infix的内部函数定义
//类Infix的构造函数
Infix::Infix()
{

	OPTR.Push('#');
}

//中缀表达式计算函数的定义
void Infix::InExpress(string &exp)                               
{
	Priority compare;
	int i=0,temp;
	while (!OPTR.Empty())
	{
		if (exp[i]<='9' && exp[i]>='0')             //若为数字,则进行入栈处理
		{
			temp=exp[i]-48;
			while (exp[i+1]<='9' && exp[i+1]>='0')
			{
				temp=(temp*10)+(exp[i+1]-48);
                i++;
			}
            OPND.Push(temp);
            i++;
		}
		else 
		{if(exp[i]=='+'||exp[i]=='-'||exp[i]=='*'||exp[i]=='/'||exp[i]=='('||exp[i]==')'||exp[i]=='#') //若为运算符,则分情况处理
			{
				switch (compare.PriOPTR(OPTR.GetTop(),exp[i])){
                case '<':
					OPTR.Push(exp[i]);
					i++;
					break;
				case '=':
					OPTR.Pop();
					i++;
					break;
				case '>':
					cout<<'\n';
					Theta=OPTR.Pop();
					b=OPND.Pop();
					a=OPND.Pop();
					OPND.Push(Operate(a,Theta,b));
					break;
				default:
					cout<<"Input Error";
					cin.clear();     
                    cin.ignore(); 
	                char a=cin.get();
					exit(0);
				}
			}
		else i++;}
		
	}
	if (OPND.Empty()){
		cout <<"Input Error";
	    cin.clear();     
        cin.ignore(); 
	    char a=cin.get();
		exit(0);
	}
	else cout <<"\n The Result is"<<OPND.GetTop();
}


//两个元素的运算函数
int Infix::Operate(int a, char theta, int b)
{
	switch (theta){
            case '+':
				return (a+b);
	            break;
			case '-':
				return (a-b);
				break;
			case '*':
				return (a*b);
				break;
			case '/':
				return (a/b);
				break;
	}
}

⌨️ 快捷键说明

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