逆波兰计算器:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define Stack_Init_Size 20
#define Stack_Increasement 10
#define Max_Buffer_Size 10
typedef double Elemtype;
typedef struct {
Elemtype *base;
Elemtype *top;
int stackSize;
}sqStack;
void 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;
}
void push(sqStack *s,Elemtype e){
if(s->top - s->base>=s->stackSize){
s->base=(Elemtype *)realloc(s->base,(s->stackSize+Stack_Increasement)*sizeof(Elemtype));
if(!s->base)
exit(0);
}
*(s->top)=e;
s->top++;
}
void pop(sqStack *s,Elemtype *e){
if(s->top==s->base)
exit(0);
s->top--;
*e=*(s->top);
}
int stackLen(sqStack s){
return (s.top - s.base);
}
int isEmpty(sqStack s){
return (s.top==s.base);
}
int main(){
sqStack s;
initStack(&s);
char c;
double d,e;
char buffer[Max_Buffer_Size];
int i=0;
printf("请输入所要计算表达式的逆波兰表达式,数字(包括小数)之间用空格分开,以#表示结束!\n");
scanf("%c",&c);
while(c!='#'){
while(isdigit(c)||c=='.'){
buffer[i++]=c;
buffer[i]='\0';
if(i>=10){
printf("\n出错!超过最大缓冲区大小!\n");
return -1;
}
scanf("%c",&c);
if(c==' '){
d=atof(buffer);
push(&s,d);
i=0;
break;
}
}
switch(c){
case '+':
pop(&s,&d);
pop(&s,&e);
push(&s,d+e);
break;
case '-':
pop(&s,&d);
pop(&s,&e);
push(&s,e-d);
break;
case '*':
pop(&s,&d);
pop(&s,&e);
push(&s,d*e);
break;
case '/':
pop(&s,&d);
pop(&s,&e);
if(e!=0){
push(&s,e/d);
}
else{
printf("\n出错,分母不能为0!");
return -1;
}
break;
}
scanf("%c",&c);
}
pop(&s,&d);
printf("\n最终结果为:%f\n",d);
return 0;
}