运行有问题
#include<stdio.h>#include<stdlib.h>
#define stackmaxsize 100
#define stackincert 10
typedef struct
{
float *top;
float *base;
int stacksize;
}Stack;
int stackinit_num(Stack *s)
{
s->base=(float*)malloc(stackmaxsize*sizeof(float));
if(s->base==NULL) exit(1);
s->top=s->base;
s->stacksize=stackmaxsize;
return 0;
}
int stackinit_flag(Stack *p)
{
p->base=(char*)malloc(stackmaxsize*sizeof(char));
if(p->base==NULL) exit(1);
p->top=p->base;
p->stacksize=stackmaxsize;
return 0;
}
int push_num(Stack *s,float x)
{
if(s->top-s->base>=s->stacksize)
{
s->base=(float*)realloc(s->base,(s->stacksize+stackincert)*sizeof(float));
if(s->base==NULL) exit(1);
s->top=s->base+s->stacksize;
s->stacksize+=stackincert;
}
*(s->top++)=x;
return 0;
}
int push_flag(Stack *w,char x)
{
if(w->top-w->base>=w->stacksize)
{
w->base=(char*)realloc(w->base,(w->stacksize+stackincert)*sizeof(char));
if(w->base==NULL) exit(1);
w->top=w->base+w->stacksize;
w->stacksize+=stackincert;
}
*(w->top++)=x;
return 0;
}
int pop_num(Stack *s_num,float *x)
{
if(s_num->top==s_num->base) exit(1);
*x=*(--s_num->top);
return 0;
}
int pop_flag(Stack *s_flag,char *x)
{
if(s_flag->top==s_flag->base) exit(1);
*x=*(--s_flag->top);
return 0;
}
int gettop_flag(Stack s,char *x)
{
if(s.top==s.base) exit(1);
*x=*(--s.top);
return 0;
}
int compare(char *p1,char *p2)
{
if(*p1=='+'||*p1=='-')
{
if(*p2=='+'||*p2=='-'||*p2==')'||*p2=='#') return 1;
else return -1;
}
else if(*p1=='*'||*p1=='/')
{
if(*p2=='(') return -1;
else return 1;
}
else if(*p1=='(')
{
if(*p2==')') return 0;
else if(*p2=='#') {printf("表达式错误");exit(1);}
else return -1;
}
else if(*p1==')')
{
if(*p2=='(') {printf("表达式错误");exit(1);}
else return 1;
}
else if(*p1=='#')
{
if(*p2==')') {printf("表达式错误");exit(1);}
else if(*p2=='=') return 0;
else return -1;
}
else {printf("表达式错误");exit(1);}
}
int function(float a,char ch,float b,float *y)
{
if(ch='+') *y=a+b;
else if(ch=='-') *y=a-b;
else if(ch=='*') *y=a*b;
else if(ch='/') *y=a/b;
else {printf("error");exit(1);}
return 0;
}
int main()
{
Stack s_num,s_flag;
char ch1,ch2;
float a,b,c;
stackinit_flag(&s_flag);
push_flag(&s_flag,'#');
stackinit_num(&s_num);
ch1=getchar();
gettop_flag(s_flag,&ch2);
while(ch1!='#'||ch2!='#')
{
if(ch1!='+'&&ch1!='-'&&ch1!='*'&&ch1!='/')
{push_num(&s_num,ch1);ch1=getchar();}
else
{
switch(compare(&ch2,&ch1))
{
case -1: push_flag(&s_flag,ch1); break;
case 0: pop_flag(&s_flag,&ch2);break;
case 1: pop_flag(&s_flag,&ch2);pop_num(&s_num,&a);
pop_num(&s_num,&b); function(a,ch2,b,&c);
push_num(&s_num,c); break;
default: printf("error");break;
}
}
gettop_flag(s_flag,&ch2);
ch1=getchar();
}
printf("%f",*(s_num.base));
return 0;
}
//计算简单表达式的值