算法表达式求值

摘要:

两个栈:操作数栈OPND,操作符号栈OPTR

在表达式后加#

符号栈初始化时#入栈

每读一个字符:

当它是#并且符号栈栈顶也是#时结束算法

当它是操作数时,进数栈

当它是符号时:

1.如果符号栈顶的优先级小于它,进符号栈

2.如果符号栈顶的优先级大于它,出两个数,出一个符号,计算后入数栈

3.如果与符号栈顶优先级相等,那说明是栈顶为(,它是),(出栈

// ExpressValue.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <stack>
#include <map>
using namespace std;
int operate(int p,char opera,int q)
{
	switch(opera)
    {
	case '+': return q+p;
	case '-': return p-q;
	case '*': return p*q;
	case '/': return p/q;
    }
	throw "no this operation:" + opera;
}
bool in(char c,char array[]){
	int length = strlen(array);
	for(int i=0;i<length;i++)
		if(c==array[i])return true;
	return false;
}


typedef map<char,int> MAP;
MAP opt;
char t[][7]={
	{'>','>','<','<','<','>','>'},
	{'>','>','<','<','<','>','>'},
	{'>','>','>','>','<','>','>'},
	{'>','>','>','>','<','>','>'},
	{'<','<','<','<','<','=',0},
	{'>','>','>','>',0,'>','>'},
	{'<','<','<','<','<',0,'='}
    
	};
char  precede(char a,char b){
	
	return t[opt[a]][opt[b]];
}
int main(int argc, char* argv[])
{
	freopen("i://t.txt","r",stdin);
	char op[]={'+','-','*','/','(',')','#',0};
	opt.insert(MAP::value_type('+',0));
	opt.insert(MAP::value_type('-',1));
	opt.insert(MAP::value_type('*',2));
	opt.insert(MAP::value_type('/',3));
	opt.insert(MAP::value_type('(',4));
	opt.insert(MAP::value_type(')',5));
	opt.insert(MAP::value_type('#',6));
	

	while(1){
	
	stack<char> optr,opnd;
	optr.push('#');
	char c = getchar();
	if(c=='e')return 0;
	while(!(c=='#'&&optr.top()=='#')){
		if(!in(c,op)){
			opnd.push(c-'0');
			c = getchar();
		}
		else{

			switch(precede(optr.top(),c)){
			case '<':
				optr.push(c);
				c = getchar();
				break;
			case '=':
				optr.pop();
				c = getchar();
				break;
			case '>':
				int a = opnd.top();
				opnd.pop();
				int b = opnd.top();
				opnd.pop();
				char ope = optr.top();
				optr.pop();
				opnd.push(operate(b,ope,a));
				//printf("[%d %c %d = %d]",b,ope,a,operate(b,ope,a));
				break;
			

			}

		}
	}
	printf("%d\n",opnd.top());
	}
	
	return 0;
}

测试数据:

1+1+2#
2*3+5#
1#
4/2+6#
6*2*(2+5)#
6*2*(2+5)/7#
1+8/(1+1)#
2*(4+4)/8+8-2#
8*9/3-8#
end

转载于:https://www.cnblogs.com/yangyh/archive/2011/05/14/2046522.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值