Expression

//while (從exp讀取字符ch,ch!='\0')
//{    若ch爲數字,將後續的所有數字均依次存放到postexp中,並以字符“#”標誌數值串結束。
//若ch爲左括號“(”,則將此括號進棧到運算符棧op中。
//               若ch爲右括號“)”,則將運算符棧op中左括號“(”以前的運算符依次出棧並存放到postexp中,然後將左括號“(”刪除。
//               若ch運算符優先級小於或等於op棧頂運算符的優先級 (除棧頂運算符爲“(”外)的優先級,則依次出棧並存入到postexp中,然後將ch進棧。
//}
//若字符串exp掃描完畢,則將運算棧op中的所有運算符依次出棧並存放到postexp中。最後得到後綴表達式postexp。



#include <stdlib.h>

float ComputeValue(const char postExp[])
{
	struct
	{
		double	data[20];
		int		top;
	} St;
	St.top = -1;

	int index = 0;
	char ch = postExp[index];

	while (ch != '\0')
	{
		double tmp = 0.0;
		switch (ch)
		{
		case '+':
			St.data[St.top - 1] = St.data[St.top - 1] + St.data[St.top];
			--St.top;
			break;
			
		case '-':
			St.data[St.top - 1] = St.data[St.top - 1] - St.data[St.top];
			--St.top;
			break;
			
		case '/':
			if (St.data[St.top] != 0)
			{
				St.data[St.top - 1] = St.data[St.top - 1] / St.data[St.top];
				--St.top;
			}
			else
			{
				exit(0);
			}

			break;

		default:
			double d = 0.0;

			while (ch <= '9' && ch >= '0')
			{
				d = 10 * d + ch - '0';
				
				++index;
				ch = postExp[index];
			}

			++St.top;
			St.data[St.top] = d;
			break;
		}

		++index;
		ch = postExp[index];
	}


	return St.data[St.top];
}

void Trans(const char exp[], char postExp[])
{
	struct  
	{
		char	data[50];
		int		top;
	} Op;
	Op.top = -1;
	
	int expIndex = 0, index = 0;
	char ch = exp[expIndex];
	
	while (ch != '\0')
	{
		switch (ch)
		{
		case '(':
			++Op.top; 
			Op.data[Op.top] = ch;
			break;
			
		case ')':
			while(Op.data[Op.top] != '(')
			{
				postExp[index] = Op.data[Op.top];
				++index;
				--Op.top;
			}
			
			--Op.top;
			break;
			
		case '+': case '-':
			while(Op.top != -1 && Op.data[Op.top] != '(') // zui di you xian ji
			{
				postExp[index] = Op.data[Op.top];
				++index;
				--Op.top;
			}
			
			++Op.top;
			Op.data[Op.top] = ch;
			break;
			
		case '*': case '/':
			while (Op.data[Op.top] == '*' || Op.data[Op.top] == '/') // 最高優先級
			{
				postExp[index] = Op.data[Op.top];
				++index;
				--Op.top;
			}
			
			++Op.top;
			Op.data[Op.top] = ch;
			
			break;
			
		case ' ':
			break;
			
		default:
			while (ch <= '9' && ch >= '0')
			{
				postExp[index] = ch;
				++index;
				
				++expIndex;
				ch = exp[expIndex];
			}
			
			--expIndex; 
			postExp[index] = '#';
			++index;
			
			break;
		}
		
		++expIndex;
		ch = exp[expIndex];
	}
	
	while (Op.top != -1)
	{
		postExp[index] = Op.data[Op.top];
		++index; --Op.top;
	}
}

int main()
{
	char exp[50] = "(56-20)/(4+2)";
	char postExp[50] = "";
	
	Trans(exp, postExp);

	char test[50] = "56#20#-4#2#+/";
	ComputeValue(test);
	return 0;
}

 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章