#include <stdio.h>
#include <stdlib.h> /* for atof() */
#include <ctype.h>
#define MAXOP 100 /* max size of operand and operator */
#define NUMBER '0' /* signal that a number was found */
#define MAXVAL 100 /* maxmium depth of value stack */
#define BUFSIZE 100
int getop(char []);
void push(double);
double pop(void);
int getch(void);
void ungetch(int);
int sp = 0; /* next free stack position */
double val[MAXVAL]; /* value stack */
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */
/* reverse Polish Calculator */
main()
{
int type;
double op2;
char s[MAXOP];
while ((type = getop(s)) != EOF) {
switch (type) {
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if (op2 != 0.0)
push(pop() / op2);
else
printf("error: zero divisor\n");
break;
case '\n':
printf("\t%.8g\n",pop());
break;
default:
printf("error: unknown command %s\n",s);
break;
}
}
return 0;
}
/* push: push f onto value stack */
void push(double f)
{
if (sp < MAXVAL)
val[sp++] = f;
else
printf("error: stack full,can't push %g\n",f);
}
/* pop: pop and return top value from stack */
double pop(void)
{
if (sp > 0)
return val[--sp];
else {
printf("error: stack empty\n");
return 0.0;
}
}
/* getop: get next character or numeric oprand */
int getop(char s[])
{
//寮濮嬭瘯鍥捐鍙栦竴涓搷浣滄暟鎴栦竴涓搷浣滅
int i,c;
//蹇界暐絀烘牸錛氱洿鍒拌鍒伴潪絀哄瓧絎?BR> while ((s[0] = c = getch()) == ' ' || c == '\t')
;
//鏈熬鍔犲瓧絎︿覆緇撴潫鏍囪瘑
s[1] = '\0';
//if (!(s[0] == '-' && bufp == 1))
// if (!isdigit(c) && c != '.')
// return c;
//濡傛灉璇誨埌鐨勪笉鏄暟瀛楀茍涓斾笉鏄皬鏁扮偣錛岃〃紺鴻鍒頒簡涓涓搷浣滅
if (!isdigit(c) && c != '.')
return c; /* not a number */
i = 0;
//濡傛灉璇誨埌浜嗘暟瀛楋紝緇х畫璇誨彇鐩村埌璇誨埌闈炴暟瀛楀瓧絎?BR> if (isdigit(c)) /* collect integer part */
while (isdigit(s[++i] = c = getch()))
;
//濡傛灉涓婇潰璇誨彇鍒扮殑闈炴暟瀛楀瓧絎︽槸灝忔暟鐐癸紝緇х畫璇誨彇鐩村埌璇誨彇鍒伴潪鏁板瓧瀛楃
if (c == '.') /* collect fraction part */
while (isdigit(s[++i] = c = getch()))
;
//鍦╯緇撳熬鍓嶄竴浣嶅姞緇撴潫鏍囪瘑
s[i] = '\0';
//濡傛灉鏈鍒版湯灝撅紝鎶婃渶鍚庤鍒扮殑閭d釜瀛楃鏀懼埌杈撳叆緙撳啿瀛楃鏁扮粍buf涓?BR> if (c != EOF)
ungetch(c);
return NUMBER;
}
int getch(void) /* get a (possibly pushed-back) character */
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) /* push character back on input */
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}