`
java-mans
  • 浏览: 11342074 次
文章分类
社区版块
存档分类
最新评论

NYOJ-35-表达式求值

 
阅读更多

NYOJ-35-表达式求值

http://acm.nyist.net/JudgeOnline/problem.php?pid=35

很好的一题,利用栈来计算表达式的值

四则运算的规则:1.先乘除,后加减;2.从左算到右;3.先括号内,后括号外

注意把字符串转换成浮点数可以使用atof函数


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int map[7][7]=    //算符间的优先关系,100表示不会出现的情况
{
	{1,1,-1,-1,-1,1,1},
	{1,1,-1,-1,-1,1,1},
	{1,1,1,1,-1,1,1},
	{1,1,1,1,-1,1,1},
	{-1,-1,-1,-1,-1,0,100},
	{1,1,1,1,100,1,1},
	{-1,-1,-1,-1,-1,100,0}
};
int cam(char c)
{
	switch(c)
	{
	case '+':return 0;
	case '-':return 1;
	case '*':return 2;
	case '/':return 3;
	case '(':return 4;
	case ')':return 5;
	case '#':return 6;
	}
}
double sol(double x,char c,double y)
{
	switch(c)
	{
	case '+':return x+y;
	case '-':return x-y;
	case '*':return x*y;
	case '/':return x/y;
	}
}
int z(char c)
{
	if('0'<=c&&c<='9'||c=='.')
    return 1;
	if(c==' ')
	return -1;
	return 0;
}
char str[1005];
char optr[1005];
double opnd[1005];
int main()
{
	int t1,t2,k,len;
	char ch,zz;
	int temp1,temp2;
	double a,b;
	int t;
	scanf("%d",&t);
	getchar();
	while(t--)
	{
		gets(str);
		len=strlen(str);
		str[len-1]='#'; //处理的等于号
		t1=t2=k=0;
		optr[t1++]='#';
		ch=str[k++];
	    while(ch!='#'||optr[t1-1]!='#')
		{
	        if(z(ch)==1)  //操作数入栈
			{
				opnd[t2++]=atof(&str[k-1]); //把字符串转换成浮点数
				while(z(str[k])==1)
				k++;
				ch=str[k++];
			}
			else if(z(ch)==-1)
			ch=str[k++];
			else 
			{
				temp1=cam(optr[t1-1]);
				temp2=cam(ch);
				if(map[temp1][temp2]==-1)  //栈顶元素优先权低
				{
                      optr[t1++]=ch;
					  ch=str[k++];
				}
				else if(map[temp1][temp2]==0) //脱括号并接受下一个字符
				{
                      t1--;
					  ch=str[k++];
				}
				else    //退栈并将运算结果
				{
                      zz=optr[--t1];
					  a=opnd[--t2];
					  b=opnd[--t2];
					  opnd[t2++]=sol(b,zz,a);
				}
			}
		}
		printf("%.2lf\n",opnd[0]);
	}
	return 0;
}
				






分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics