1. 程式人生 > 其它 >逆波蘭計算器

逆波蘭計算器

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>//用來判斷字元是不是數字 
#define OK 1
#define ERROR 0
#define MAX_INIT_SIZE 100
#define STACKINCREMENT 10
#define MAXBUFFER 10
typedef double ElemType;
typedef int Status;
typedef struct{
    ElemType *top;
    ElemType 
*base; int StackSize; }SqStack; //建立棧 Status InitStack(SqStack *S){ S->base=(ElemType *)malloc(MAX_INIT_SIZE*sizeof(ElemType));\ if(!S->base) return ERROR; S->top=S->base; S->StackSize=MAX_INIT_SIZE; return OK; } Status 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->StackSize+S->base; S->StackSize+=STACKINCREMENT; } *(S->top)=e; S
->top++; } void Pop(SqStack *S,ElemType *e){ if(S->top==S->base) return; *e=*--(S->top); } int StackLen(SqStack S){ return S.top-S.base; } void ClearStack(SqStack *S){ S->top=S->base; } void DestroyStack(SqStack *S){ int i; int len=S->StackSize; for(i=0;i<len;i++){ free(S->top); S->top--; } S->top=S->base=NULL; S->StackSize=0; } int main(){ SqStack S; int i=0; ElemType d,e; char c,str[MAXBUFFER]; InitStack(&S); printf("請輸入逆波蘭式以#結束:\n"); scanf("%c",&c); while(c!='#'){ while(isdigit(c)||c=='.'){ str[i++]=c; str[i]=0;//給字串新增結束符,為呼叫atof函式做準備 if(i>=10){ printf("出錯:輸入的單個數據過大!"); return -1; } scanf("%c",&c); if(c==' '){ d=atof(str);//將字串轉換成雙精度浮點型 Push(&S,d); i=0; break; } } if(c=='+'){ Pop(&S,&d); Pop(&S,&e); Push(&S,d+e); } else if(c=='-'){ Pop(&S,&d); Pop(&S,&e); Push(&S,e-d); } else if(c=='*'){ Pop(&S,&d); Pop(&S,&e); Push(&S,e*d); } else if(c=='/'){ Pop(&S,&d); Pop(&S,&e); if(d==0){ printf("程式出錯,分母為0!"); return -1; } Push(&S,e/d); } scanf("%c",&c); } Pop(&S,&d); printf("%lf",d); }

舉例:1 2 - 3 4 * *

過程:接收1後存如str陣列,再接收空格後,將1轉換成雙精度浮點型然後入棧S,接著接收2,同上操作,此時棧內有兩個數字1和2,繼續接收到了‘-’號,此時進行減法運算(操作是按順序出棧,則d=2,e=1,計算完後得-1,入棧,此時棧內只有-1),接著接收3,4,*,同上操作,此時結果為12入棧,此時棧內有兩個數字-1和12,接著接收*,然後運算,此時結果為-12入棧,棧內只有-12;

最後出棧列印;