#include
#include
#include
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
#define MAXBUFFER 10
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+=STACKINCREMENT;
}
*S.top++=e;
}
Pop(SqStack &S,ElemType &e)
{
if (S.top==S.base)
{
return -1;
}
e=*(--S.top);
}
int main()
{
SqStack s;
char c;
double d,e;
char str[MAXBUFFER];
int i=0;
InitStack(s);
printf("请按逆波兰表达式输入待计算数据,数据与数据之间用空格隔开,以#号作为结尾\n");
scanf("%c",&c);
while (c!='#')
{
while (isdigit(c)||c=='.')
{
str[i++]=c;
str[i]='\0';
if (i>=10)
{
printf("出错:输入的单个数据过大!\n");
return -1;
}
scanf("%c",&c);
if (c==' ')
{
d=atof(str);
Push(s,d);
i=0;
break;
}
}
switch(c)
{
case '+':
Pop(s,e);
Pop(s,d);
Push(s,d+e);
break;
case '-':
Pop(s,e);
Pop(s,d);
Push(s,d-e);
break;
case '*':
Pop(s,e);
Pop(s,d);
Push(s,d*e);
break;
case '/':
Pop(s,e);
Pop(s,d);
if (e!=0)
{
Push(s,d/e);
}
else
{
printf("\n出错:除数为零!\n");
return -1;
}
break;
}
scanf("%c",&c);
}
Pop(s,d);
printf("\n最终的计算结果为:%f\n",d);
return 0;
}