改完了,几个简单的语法错误#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 20
#define MAXBUFFER 20
typedef struct
{
float *base;
float *top;
int stackSize;
}FStack;
typedef struct
{
char *base;
char *top;
int stackSize;
}CStack;
FStack OPND;
CStack OPTR;
void InitStack_Float(FStack *s)
{
s->base = (float *)malloc(STACK_INIT_SIZE * sizeof(float));
if( !s->base )
exit(0);
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
void InitStack_Char(CStack *s)
{
s->base = (char *)malloc(STACK_INIT_SIZE * sizeof(char));
if( !s->base )
exit(0);
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
void Push_F(FStack *s, float e)
{
if( s->top - s->base >= s->stackSize )
{
s->base = (float *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(float));
if( !s->base )
exit(0);
s->top = s->base + s->stackSize;
s->stackSize = s->stackSize + STACKINCREMENT;
}
*(s->top) = e;
s->top++;
}
void Push_C(CStack *s,char e)
{
if( s->top - s->base >= s->stackSize )
{
s->base = (char *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(char));
if( !s->base )
exit(0);
s->top = s->base + s->stackSize;
s->stackSize = s->stackSize + STACKINCREMENT;
}
*(s->top) = e;
s->top++;
}
void Pop_F(FStack *s, float *e)
{
if( s->top == s->base )
return;
*e = *--(s->top);
}
void Pop_C(CStack *s, char *e)
{
if( s->top == s->base )
return;
*e = *--(s->top);
}
int in(char ch)
{
return (ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='#');
}
int StackLen(FStack s)
{
return (s.top - s.base);
}
float GetTop_F(FStack s) //取栈顶元素
{
float e;
if(s.top == s.base)
{
return 0;
}
e = *(s.top - 1);
return e;
}
char GetTop_C(CStack s)
{
char e;
if(s.top == s.base)
{
return 0;
}
e = *(s.top - 1);
return e;
}
char Precede(char theta1,char theta2) //运算符优先级
{
int a,b;
switch(theta1)
{
case'=':
a=0;
break;
case'(':
a=1;
break;
case'+':
case'-':
a=3;
break;
case'*':
case'/':
case'%':
a=5;
break;
case')':
a=6;
break;
}
switch(theta2)
{
case'=':
b=0;
break;
case'(':
b=6;
break;
case'+':
case'-':
b=2;
break;
case'*':
case'/':
case'%':
b=4;
break;
case')':
b=1;
break;
}
if(a<b)
return '<';
else if(a==b)
return'=';
else
return '>';
}
float Operators(float a,char c,float b)
{
float value;
switch(c)
{
case'+':
value = a + b;
break;
case'-':
value = a - b;
break;
case'*':
value = a * b;
break;
case'/':
value = a / b;
break;
}
return value;
}
float EvalueteExpression()
{
char c,theta,x;
float a,b;
c = getchar();
while(c!='#'||GetTop_C(OPTR)!='#')
{
if(!in(c))
{
Push_F(&OPND,c);
c = getchar();
}
else
{
switch(Precede(GetTop_C(OPTR),c))
{
case'<':
Push_C(&OPTR,c);
c = getchar();
break;
case'=':
Pop_C(&OPTR,&x);
c = getchar();
break;
case'>':
Pop_C(&OPTR,&theta);
Pop_F(&OPND,&b);
Pop_F(&OPND,&a);
Push_F(&OPND,Operators(a,theta,b));
}
}
}
return GetTop_F(OPND);
}
int main(){
printf("请输入正确的表达式以'#'结尾: \n");
InitStack_Char(&OPTR);
Push_C(&OPTR,'#');
InitStack_Float(&OPND);
printf("表达式结果为: %f",EvalueteExpression());
return 0;
}
|