mmd 感觉脑子不够用了。还是用笨方法:一步一步写注释。
#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;
//忽略空格:直到读到非空字符
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;
//如果读到了数字,继续读取直到读到非数字字符
if (isdigit(c)) /* collect integer part */
while (isdigit(s[++i] = c = getch()))
;
//如果上面读取到的非数字字符是小数点,继续读取直到读取到非数字字符
if (c == '.') /* collect fraction part */
while (isdigit(s[++i] = c = getch()))
;
//在s结尾前一位加结束标识
s[i] = '\0';
//如果未读到末尾,把最后读到的那个字符放到输入缓冲字符数组buf中
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;
}