表达式求值问题

 这里限定的表达式求值问题是:

用户输入一个包含“+”、“-”、“*”、“/”、正整数和圆括号的合法数学表达式,计算该表达式的运算结果。

算术表达式求值过程是:

STEP 1:先将算术表达式转换成后缀表达式。

STEP 2:然后对该后缀表达式求值。

实验说明:在设计相关算法中用到栈,这里采用顺序栈存储结构。

中缀表达式exp ==》后缀表达式postexp伪代码如下:

表达式求值问题_第1张图片

#include 
#define MAXSIZE 100
using namespace std;
typedef struct Stack {
	char data[MAXSIZE + 1];
	int top;
}LinkStack;
int Push(LinkStack &S, char m) {
	if (S.top == MAXSIZE)
		return 0;
	S.data[++S.top] = m;
	return 1;
}
int Pop(LinkStack &S, char &m) {
	if (S.top == 0) return 0;
	m = S.data[S.top];
	S.top--;
	return 1;
}

char GetTop(LinkStack S) {
	char a;
	a = S.data[S.top];
	return a;
}

double operate(char ch, double x, double y)
{
	double z;
	switch (ch)
	{
	case '+': z = x + y; break;
	case '-': z = x - y; break;
	case '*': z = x * y; break;
	case '/': z = x / y; break;
	}
	return((char)z);
}

int precede(char p1, char p2)
{
	int flag = -2;
	switch (p1)
	{
	case '+':
		if (p2 == '*' || p2 == '/' || p2 == '(') flag = -1;
		else flag = 1;
		break;
	case '-':
		if (p2 == '*' || p2 == '/' || p2 == '(') flag = -1;
		else flag = 1;
		break;
	case '*':
		if (p2 == '(') flag = -1;
		else flag = 1;
		break;
	case '/':
		if (p2 == '(') flag = -1;
		else flag = 1;
		break;
	case '(': if (p2 == ')') flag = 0;
			  else if (p2 == '#')printf("error 1 operator!\n");
			  else flag = -1;
			  break;
	case ')': if (p2 == '(')printf("error 2 operator!\n");
			  else flag = 1;
			  break;
	case '#': if (p2 == ')')printf("error 3 operator!\n");
			  else if (p2 == '#')
				  flag = 0;
			  else
				  flag = -1;
		break;
	}
	return(flag);
}

double EvaluateExpression(char a[])
{
	Stack S1, S2;
	S1.top = 0;
	S2.top = 0;
	double x, y, z;
	char x1, x2;
	char r, ch;
	int I = 0;
	Push(S1, '#');
	r = a[I];
	while (r != '#' || GetTop(S1) != '#')
	{
		if (r <= '9' && r >= '0')
		{
			x = 0;
			while (r <= '9' && r >= '0')
			{
				x = x * 10 + r - '0';
				r = a[++I];
			}
			Push(S2, x);
		}
		else
			switch (precede(GetTop(S1), r))
			{
			case -1:
				Push(S1, r); 
				r = a[++I]; 
				break; //把运算符放进栈1  
			case 0:
				Pop(S1, ch);
				r = a[++I];
				break; //弹出一个运算符  
			case 1:
				Pop(S1, ch); Pop(S2, x1); Pop(S2, x2);
				Push(S2, operate(ch, x2, x1));   
				r = a[I];
				break;
			}
	}
	return(GetTop(S2));
}
int main()
{
	int length;
	int t = 0;
	char tmp[1000] = "1+2#";
	do {
		printf("Please cin, '#' is over\n");
		//cin >> tmp;
		length = strlen(tmp);
		for (int i = 0; i= '0') && (tmp[i] <= '9')) || tmp[i] == '+' 
				|| tmp[i] == '-' || tmp[i] == '*' || tmp[i] == '/' || tmp[i] == '#')
				t = 0; 
			else if (tmp[length - 1] != '#') {
				t = 1; continue;
			}
			else t = 1; continue;
		}
		if (t == 1) cout << "出错!" << endl;
	} while (t == 1);
	if (t == 0) {
		double rst = EvaluateExpression(tmp);
		cout << "结果为:" << rst << endl;
		system("pause");
	}
	return 0;
}

以"1+2#"为例:

表达式求值问题_第2张图片

你可能感兴趣的:(表达式求值问题)