2 * Exercise 4-5. Add access to library functions like sin, exp, and pow. See
3 * <math.h> in Appendix B, Section 4.
7 #include <stdlib.h> /* for atof() */
11 #define MAXOP 100 /* max size of operand or operator */
12 #define NUMBER '0' /* signal that a number was found */
13 #define IDENTIFIER '1' /* signal that an identifier was found */
18 double printtop(void);
23 /* reverse Polish calculator */
28 while ((type = getop(s)) != EOF) {
34 if (strcmp(s, "sin") == 0)
36 else if (strcmp(s, "cos") == 0)
38 else if (strcmp(s, "exp") == 0)
56 printf("error: zero divisor\n");
61 push((int) pop() % (int) op2);
63 printf("error: zero divisor\n");
66 printf("\t%.8g\n", printtop());
70 printf("error: can't duplicate\n");
74 printf("error: swap failed, stack needs two numbers\n");
80 printf("\t%.8g\n", pop());
83 printf("error: unknown command %s\n", s);
89 #define MAXVAL 100 /* maximum depth of val stack */
91 int sp = 0; /* next free stack position */
92 double val[MAXVAL]; /* value stack */
94 /* push: push f onto value stack */
95 void push (double f) {
99 printf ("error: stack full, can't push %g\n", f);
102 /* pop: pop and return top value from stack */
107 printf("error: stack empty\n");
112 /* printtop: print the top value of the stack without popping it */
113 double printtop(void) {
117 printf("error: stack empty\n");
122 /* duplicate: duplicate the top value of the stack
123 * return 1 if successful, 0 on failure */
124 int duplicate(void) {
127 } else if (sp >= MAXVAL) {
136 /* swap: swap the top two values of the stack
137 * return 1 if successful, 0 on failure */
140 int temp = val[sp-1];
141 val[sp-1] = val[sp-2];
148 /* clear: clear the stack */
158 /* getop: get next operator or numeric operand */
159 int getop(char s[]) {
161 while ((s[0] = c = getch()) == ' ' || c == '\t')
166 while (isalpha(s[++i] = c = getch()))
173 /* negative number or minus */
175 s[++i] = c = getch();
176 if (!isdigit(c) && c != '.') {
181 if (!isdigit(c) && c != '.')
182 return c; /* not a number */
183 if (isdigit(c)) /* collect integer part */
184 while (isdigit(s[++i] = c = getch()))
186 if (c == '.') /* collect fraction part */
187 while (isdigit(s[++i] = c = getch()))
197 char buf[BUFSIZE]; /* buffer for ungetch */
200 /* get a (possibly pushed back) character */
202 return (bufp > 0) ? buf[--bufp] : getchar();
205 /* push character back on input */
206 void ungetch(int c) {
208 printf("ungetch: too many characters\n");
214 void printstack(void);
216 void printstack(void) {
217 for (int i = 0; i < sp; i++)
218 printf("%g ", val[i]);