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;
}

 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值