表达式运算器的实现原理(快速优先法)

类别:VC语言 点击:0 评论:0 推荐:
int scan(char *src,float *num,char *sign,int *level)
{
int count=0,stdlevel=0;
while(*src)
{
if(*src=='(')stdlevel+=2;
if(*src==')')stdlevel-=2;
if(*src=='+' || *src=='-'){sign[count]=*src;level[count]=stdlevel;}
if(*src=='*' || *src=='/'){sign[count]=*src;level[count]=stdlevel+1;}
if(*src>='0' && *src<='9')
{
num[count]=0;
while(*src>='0' && *src<='9')
{
num[count]=num[count]*10+*src-'0';src++;
}
count++;src--;
}
src++;
}
return count;
}
float exp(int index,float *num,char *sign,int *level)
{
int k;
float mid,left,right;
if(index<2)mid=num[0];
else if(index<3){left=num[0];right=num[1];k=1;}
else
{
int min=25536,d;
k=index-1;
for(d=index-1;d>0;d--)if(min>level[d]){min=level[d];k=d;}
if(k>=2)left=exp(k,num,sign,level);
else left=num[k-1];
if(index-k>=2)right=exp(index-k,num+k,sign+k,level+k);
else right=num[index-1];
}
switch(sign[k])
{
case '+':mid=left+right;break;
case '-':mid=left-right;break;
case '*':mid=left*right;break;
case '/':mid=left/right;break;
}
return mid;
}

main()
{
char sign[100],*src="1+2*(2*(5-2)-4)/2";/*"(1+2)*3-(4-5*(6/(7+8)-9))*10-11/12";*/
int count=0,k,level[100];
float num[100],last;
count=scan(src,num,sign,level);
last=exp(count,num,sign,level);
clrscr();
printf("\nlast=%6.2f",last);
for(k=0;k<count;k++)
{
gotoxy(k*5+1,4);
printf("%3.0f",num[k]);
if(k>=count-1)continue;
gotoxy(k*5+5,5);
printf("%1c",sign[k+1]);
gotoxy(k*5+4,6);
printf("%2d",level[k+1]);
}
getch();
}

本文地址:http://com.8s8s.com/it/it3334.htm