学生练习:中缀表达式求值

2021/4/7 10:43:34

本文主要是介绍学生练习:中缀表达式求值,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

#include<iostream>
#define MAXSIZE 20
#define OK 1
#define ERROR 0
using namespace std;
typedef struct stack {
	char *elem;
	int top;
} Sqstack;
void initstack(Sqstack &S)
{
	S.elem=new char[MAXSIZE];
	S.top=-1;
}
int push(Sqstack &S,char e)
{
	if(S.top==MAXSIZE-1)
		return ERROR;
	S.elem[++S.top]=e;
	return OK;
}
int pop(Sqstack &S,char &e)
{
	if(S.top==-1)
		return ERROR;
	e=S.elem[S.top--];
	return OK;
}
char Getop(Sqstack S)
{
	return S.elem[S.top];
}
char precede(char ch1,char ch2)
{
	if(ch1=='#'&&(ch2=='+'||ch2=='*'))
		return '<';
	if(ch2=='#'&&(ch1=='*'||ch1=='+'))
		return '>';
	if(ch1=='('&&(ch2=='+'||ch2=='*'))//改为<
		return '<';
	if(ch2=='('&&(ch1=='+'||ch1=='*'))
		return '<';
	if(ch2==')'&&(ch1=='+'||ch1=='*'))
		return '>';
	if(ch1==')'&&(ch2=='+'||ch2=='*'))//这里是== 
		return '<';
	if(ch1=='+'&&ch2=='*')
		return '<';
	if(ch1=='*'&&ch2=='+')
		return '>';
	if(ch1=='+'&&ch2=='+')
		return '>';
	if(ch1=='*'&&ch2=='*')
		return '>';
	if(ch1=='('&&ch2==')')
		return '=';
	if(ch1=='#'&&ch2=='(')
		return '<';
}
int In(char ch)
{
	if(ch=='*'||ch=='+'||ch=='('||ch==')'||ch=='#')//
		return 1;
	else
		return 0;
}
char operate(char ch1,char ch2,char ch3)
{
	char res;
	switch(ch2) {
		case '+':
			res=(ch1-'0')+(ch3-'0')+'0';
			break;
		case '*':
			res=(ch1-'0')*(ch3-'0')+'0';
			break;
	}
	return res;
}
char fun(Sqstack &num,Sqstack &poster)
{
	initstack(num);
	initstack(poster);
	push(poster,'#');
	char ch;
	char theta;
	char ch1,ch2;
	char ch3;
	cout<<"请输入:";
	cin>>ch;
	while(ch!='#'||Getop(poster)!='#') {
		if(!In(ch)) {
			push(num,ch);
			cin>>ch;
		} else
			switch(precede(Getop(poster),ch)) {
				case '<':
					push(poster,ch);
					cin>>ch;
					break;
				case '>': 
					pop(poster,theta);
					pop(num,ch1);
					pop(num,ch2);
					push(num,operate(ch1,theta,ch2));
					break;
				case '=':
					pop(poster,ch3);
					cin>>ch;
					break;
			}
	}
	return Getop(num);
}
int main()
{
	Sqstack num,poster;
	char sub;
	sub=fun(num,poster);
	cout<<"表达式的值为:";
	cout<<sub-'0';
	cout<<endl;
	system("pause");
	return 0;
}

  



这篇关于学生练习:中缀表达式求值的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程