2 * Exercise 4-3. Given the basic framework, it's straightforward to extend the
3 * calculator. Add the modulus (%) operator and provisions for negative
8 #include <stdlib.h> /* for atof() */
10 #define MAXOP 100 /* max size of operand or operator */
11 #define NUMBER '0' /* signal that a number was found */
17 /* reverse Polish calculator */
23 while ((type = getop(s)) != EOF) {
43 printf("error: zero divisor\n");
48 push((int) pop() % (int) op2);
50 printf("error: zero divisor\n");
53 printf("\t%.8g\n", pop());
56 printf("error: unknown command %s\n", s);
62 #define MAXVAL 100 /* maximum depth of val stack */
64 int sp = 0; /* next free stack position */
65 double val[MAXVAL]; /* value stack */
67 /* push: push f onto value stack */
68 void push (double f) {
72 printf ("error: stack full, can't push %g\n", f);
75 /* pop: pop and return top value from stack */
80 printf("error: stack empty\n");
90 /* getop: get next operator or numeric operand */
93 while ((s[0] = c = getch()) == ' ' || c == '\t')
97 /* negative number or minus */
100 if (!isdigit(c) && c != '.') {
105 if (!isdigit(c) && c != '.')
106 return c; /* not a number */
107 if (isdigit(c)) /* collect integer part */
108 while (isdigit(s[++i] = c = getch()))
110 if (c == '.') /* collect fraction part */
111 while (isdigit(s[++i] = c = getch()))
121 char buf[BUFSIZE]; /* buffer for ungetch */
124 /* get a (possibly pushed back) character */
126 return (bufp > 0) ? buf[--bufp] : getchar();
129 /* push character back on input */
130 void ungetch(int c) {
132 printf("ungetch: too many characters\n");