栈的算术优先级问题,不知道写的代码里面的问题在哪,出不来结果
#include<stdio.h>
#include<stdlib.h>
#define ok 1
#define ERROR 0
char an[7]={'+','-','*','/','(',')','='};
unsigned char Prior[7][7]=
{
// '+' '-' '*' '/' '(' ')' '='
/*'+'*/'>','>','<','<','<','>','>',
/*'-'*/'>','>','<','<','<','>','>',
/*'*'*/'>','>','>','>','<','>','>',
/*'/'*/'>','>','>','>','<','>','>',
/*'('*/'<','<','<','<','<','=',' ',
/*')'*/'>','>','>','>',' ','>','>',
/*'='*/'<','<','<','<','<',' ','='
};
char Return(char x,char y){
int a,b;
for (int i=0;i<7;i++){
if(an[i]==x)
a=i;
if(an[i]==y)
b=i;
}
return Prior[a][b];
}
typedef struct{
char *top;
char *base;
int stacksize;
}SqStack1;
typedef struct{
float *top;
float *base;
int stacksize;
}SqStack;
int ln(char c,SqStack &S)
{
switch(c){
case'1':
case'2':
case'3':
case'4':
case'5':
case'6':
case'7':
case'8':
case'9':
case'0':return 0;break;
default:return 1;break;
}//switch
}
float GetResult(float k1,float k2,char c)
{
float z;
switch(c){
case'+':z=k1+k2;break;
case'-':z=k1-k2;break;
case'*':z=k1*k2;break;
case'/':z=k1/k2;break;
}
return z;
}
float GetTopFloat(SqStack &S)
{
float e;
e=*(S.top-1);
return(e);
}
char GetTopChar(SqStack1 &S)
{
char e;
e=*(S.top-1);
return(e);
}
float PopFloat(SqStack &T)
{
if(T.top==T.base) return ERROR;
float e=*(--T.top);
return (e);
}
char PopChar(SqStack1 &T)
{
if(T.top==T.base) return ERROR;
char e=*(--T.top);
return (e);
}
int PushFloat(SqStack &S,char x){
float t;
switch(x){
case'0':t=0;break;
case'1':t=1;break;
case'2':t=2;break;
case'3':t=3;break;
case'4':t=4;break;
case'5':t=5;break;
case'6':t=6;break;
case'7':t=7;break;
case'8':t=8;break;
case'9':t=9;break;
}
if(S.top-S.base>=S.stacksize){
S.base=(float*)realloc(S.base,(S.stacksize+100)*sizeof(float));
if(!S.base) return ERROR;
S.top=S.base+S.stacksize;
S.stacksize+=100;
}
*(S.top++)=t;return ok;
}
int PushChar(SqStack1 &S,char x){
if(S.top-S.base>=S.stacksize){
S.base=(char*)realloc(S.base,(S.stacksize+100)*sizeof(char));
if(!S.base)
return ERROR;
S.top=S.base+S.stacksize;
S.stacksize+=100;}
*(S.top++)=x; return ok;
}
float tra(SqStack &S,SqStack1 &T)
{
char c;
c=getchar();
while(c!='='||GetTopChar(T)!='='){
if(!ln(c,S))
{PushFloat(S,c);c=getchar();}
else
switch(Return(GetTopChar(T),c)){
case'<':
PushChar(T,c);c=getchar();break;
case'=':
PopChar(T);c=getchar();break;
case'>':
char e1=PopChar(T);
float t1=PopFloat(S); float t2=PopFloat(S);
PushFloat(S,GetResult(t2,t1,e1));
break;
}//switch
}//while
return (GetTopFloat(S));
}
int InitStackFloat(SqStack &S){
S.base=(float *)malloc(100*sizeof(float));
if(!S.base)
return ERROR;
S.top=S.base;
S.stacksize=100;
return ok;
}
int InitStackChar(SqStack1 &S){
S.base=(char *)malloc(100*sizeof(char));
if(!S.base)
return ERROR;
S.top=S.base;
S.stacksize=100;
return ok;
}
void main(){
SqStack S;
SqStack1 T;
InitStackFloat(S);
InitStackChar(T); PushChar(T,'=');
printf("请输入:\n");
printf("%f\n",tra(S,T));
}