后缀表达式求值,有大神可以看下这个代码哪里需要改一下嘛
本帖最后由 诺诺诺诺诺诺诺 于 2017-10-27 13:30 编辑#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT10
typedef double ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stackSize;
}sqStack;
InitStack(sqStack *s)
{
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if( !s->base )
exit(0);
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
Push(sqStack *s, ElemType e)
{
if( s->top - s->base >= s->stackSize )
{
s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
if( !s->base )
exit(0);
s->top = s->base + s->stackSize;
s->stackSize = s->stackSize + STACKINCREMENT;
}
*(s->top) = e;
}
Pop(sqStack *s, ElemType *e)
{
if( s->top == s->base )
return;
*e = *--(s->top);
}
OpMember(sqStack s, char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/')
return 1;
else
return 0;
}
Operate(sqStack *s, double a, char ch, double b)
{
switch( ch )
{
case '+':
Push(&s, a+b);
break;
case '-':
Push(&s, a-b);
break;
case '*':
Push(&s, a*b);
break;
case '/':
if( b != 0 )
{
Push(&s, a/b);
}
else
{
printf("\n出错:除数为零!\n");
return -1;
}
break;
}
}
int main()
{
sqStack s;
char ch;
double a, b, result;
printf("输入后缀表达式,以#作为结束标志: \n");
scanf("%c", &ch);
InitStack( &s );
while(ch != "#")
{
if(!OpMember(s, ch))
Push(&s, ch);
else
{
Pop(&s, &b);
Pop(&s, &a);
Push(&s, Operate(&s, a, ch, b));
}
scanf("%c", &ch);
}
Pop(&s, &result);
printf("result = %f\n", result);
return 0;
}
师傅师傅说2 kankan 不用改啊{:10_254:}
页:
[1]