逆波兰表打式,编译没错,但啥都打印不出
#include<stdio.h>#include<stdlib.h>
#include<ctype.h>
#define STACK_INIT_SIZE 10//初始化栈的容量
#define STACKINCREMENT 10 //增量
#define MAXBUFFER 10
typedef double ElemType;
typedef struct sqStack
{
ElemType *top;
ElemType *base;
int stacksize;
}sqStack;
void initStack(sqStack *S)
{
S->base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!S->base==0)
exit(0);
S->top=S->base;//最开始,栈顶即为栈底
S->stacksize=STACK_INIT_SIZE;
}
void pushStack(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==0)
exit(0);
S->top=S->base+S->stacksize; //设置栈顶
S->stacksize=S->stacksize+STACKINCREMENT;//设置栈的最大容量
*(S->top)=e;
S->top++;
}
void popStack(sqStack *S,ElemType *e)
{
if(S->top==S->base)
exit(0);
*e=*(S->top--);
}
void clearStack(sqStack *S)//清空栈
{
S->top=S->base;
}
void destroyStack(sqStack *S)
{
int i,len;
len=S->stacksize;
for(i=0;i<len;i++)
{
free(S->base);
S->base++;
}
S->base=S->top=NULL;
S->stacksize=0;
}
int StackLen(sqStack *S)
{
return (S->top-S->base);//指针差即为中间元素数
}
int main()
{
sqStack S;
double a,b;
char c;
char str;
int i=0;
initStack(&S);
printf("请输入后缀表达式,数据与运算符之间用空格隔开,以#作为结束符:\n");
scanf("%c",&c);
while(c!='#')
{
while(isdigit(c)||c=='.')//函数判断c的ASCII是否为48~57,外加头文件
{
str=c;
str='\0';
if(i>=10)
{
printf("出错!输入单个数据过大!\n");
return -1;
}
scanf("%c",&c);
if(c==' ')
{
b=atof(str);//字符串转double型
pushStack(&S,b);
i=0;
break;
}
}
switch(c)
{
case '+':
popStack(&S,&a);
popStack(&S,&b);
pushStack(&S,a+b);
break;
case '-':
popStack(&S,&a);
popStack(&S,&b);
pushStack(&S,b-a);
break;
case '*':
popStack(&S,&a);
popStack(&S,&b);
pushStack(&S,a*b);
break;
case '/':
popStack(&S,&a);
popStack(&S,&b);
if(a!=0)
{
pushStack(&S,b/a);
}
else
{
printf("出错了!除数为零!/n");
return -1;
}
break;
break;
}
}
popStack(&S,&b);
printf("最终的计算结果为:%f \n",b);
return 0;
}
页:
[1]