#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define MAXOP 100 //操作數或運算符大小
#define NUMBER '0'//表示找到數的信号
#define MAXVAL 100//棧VAL的最大深度
#define BUFSIZE 100
int sp = 0;
double val[MAXVAL];//值棧
char buf[BUFSIZ];
int bufp = 0 ;
int gettop ( char s[] );//取出棧頂元素
void push (double f);//入棧操作
double pop (void);//出棧操作
int getch(void);
void ungetch( int c);
int main (){
int type;
double op2;
char s[MAXOP];
while ( ( type = gettop( s )) != EOF ){//檢查字元是不是停止符
switch (type)//檢查字元
{
case NUMBER:
push( atof (s) ); //如果傳回的是‘0’,将讀取的字元轉換成浮點數,并壓入棧中
break;
case '+':
push ( pop () + pop ());
break;
case '*':
push (pop() * pop() );
break;
case '-':
op2 = pop();
push ( pop() - op2);
break ;
case '/':
op2 = pop();
if( op2 != 0)
push (pop() / op2 );
else printf("error : zero divisor\n");
break;
case '%':
op2 = pop();
if( op2 != 0)
push (fmod (pop(),op2));
else printf("error : zero divisor\n");
break;
case '\n':
printf("result = %2.8g\n",pop());
break;
default:
printf("unknown commond %s\n",s);
break;
}
}
return 0;
}
void push (double f){//把f下推到值棧中
if ( f < MAXVAL)
val[sp++] = f;// double val[MAXVAL] 為全局變量;
else printf("error : stack full,can not push %g\n",f);
}
double pop (void){//彈出并傳回棧頂的值
if ( sp > 0)
return val[--sp];
else printf("error : stack empty!\n");
}
int gettop (char s[] ){//取下運算符或運算分量
int i,c;
while ( (s[0] = c = getch()) == ' ' || c == '\t' ) //如果讀入的是空白符或者制表符,跳過字元
;
s[1] = '\0';//将數組廢棄
if ( !isdigit(c) && c != '.' && c != '-') //如果讀入的字元 不是數字或者小數點,傳回字元
return c;
i = 0;
if ( c == '-' ){
if ( isdigit(s[++i] = c = getch() ) || c == '.')
s[i] = c;
else {
if ( c != EOF )
ungetch(c);
return '-';
}
}
if ( isdigit(s[i]) )
while ( isdigit(s[++i] = c = getch()) )
;//如果讀入的是數字,并且當下一個字元也是數字的時候 return '0';
if ( c == '.' )
while ( isdigit(s[++i] = c = getch()) )
;//如果讀取的是小數點,并且下一個字元是數字是 return '0';
s[i] = '\0';//将數組标\0
if ( c != EOF ) //如果字元不是檔案結束符,調用unget(c)函數,将字元存到緩沖區
ungetch( c );
return NUMBER;
}
int getch(void){
return (bufp > 0) ? buf[--bufp] : getchar() ;//如果緩沖數組中無值,即bufp = 0 時,getchar()讀入一個字元,否則傳回緩沖數組中存儲的值。
}
void ungetch( int c){
if ( bufp >= BUFSIZ)
printf("ungetch : too many characters!\n");
else buf[bufp++] = c ;
}