输入 :后缀表达式(可带浮点数)
输出:double型的计算结果
代码:
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #define ElemType double #define Stack_Init_Size 100 #define Increase_Size 10 #define MaxBuffer 10 typedef struct sqStack { ElemType *top; ElemType *base; int initSize; }sqStack; typedef struct sqStack *LinkStack; //初始化 void InitStack( sqStack *s ) { s->base = (LinkStack)malloc(Stack_Init_Size * sizeof(ElemType)); if(!s->base) { printf("存储空间分配失败······ "); return; } s->top = s->base; s->initSize = Stack_Init_Size; } //进栈 void Push(sqStack *s,ElemType e) { if(s->top - s->base >= s->initSize - 1) { s->base = (LinkStack)realloc(s->base,(s->initSize + Increase_Size) * sizeof(ElemType)); //第一个s->base是增加后的存储空间块的地址,第二个是增加空间之前的存储空间块地址,后面是增加过的存储空间块的大小 if(!s->base) { printf("增加存储空间失败······ "); return; } s->initSize = Increase_Size + Stack_Init_Size; } *(s->top) = e; (s->top)++; } //出栈 void Pop(sqStack *s,ElemType *e) { if(s->top == s->base) { printf("栈已空,无法进行出栈操作······ "); return; } s->top--; *e = *s->top; } //求栈的长度 int StackLen(sqStack s) { return (s.top - s.base); } //逆波兰计算器:输入逆波兰式(后缀表达式)输出结果 int main() { int i = 0,j,len; double m,n,t; char c; struct sqStack s; char str[MaxBuffer]; InitStack(&s); printf("请输入您要计算的后缀表达式,按Enter键结束(两个不同的字符之间用空格隔开): "); scanf("%c",&c); while(c != ' ') { while( (c >= '0'&&c <= '9') || c == '.') { str[i] = c; i++; // str[i] = ' '; if(i >= 10) { printf(" 输入的数字过大导致出错!!! "); return -1; } scanf("%c",&c); if( c == ' ') { t = atof(str); // printf(" t is %f ",t); Push(&s,t); i = 0; for(j = 0;j < MaxBuffer;j++) { str[j] = ' '; } break; } } switch( c ) { case '+': Pop(&s,&m); Pop(&s,&n); Push(&s,n+m); break; case '-': Pop(&s,&m); Pop(&s,&n); Push(&s,n-m); break; case '*': Pop(&s,&m); Pop(&s,&n); Push(&s,n*m); break; case '/': Pop(&s,&m); Pop(&s,&n); if( m == 0) { printf(" 除数为0,出错!!! "); return -1; } else { Push(&s,n/m); break; } } scanf("%c",&c); } Pop(&s,&t); printf(" 最终的计算结果为:%f ",t); return 0; }