Advanced calculator now supports modulus.
[C-Programming-Examples.git] / calc_adv.c
blobdaddccd21688d896db1d7974fc4b3c6c0dd0199b
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ctype.h>
5 #define MAXOP 100
6 #define NUMBER '0'
7 #define MAXVAL 100
8 #define BUFSIZE 100
10 int getop(char[]);
11 void push(double);
12 double pop(void);
14 int main()
16 int type;
17 double op2;
18 char s[MAXOP];
20 while((type = getop(s)) != EOF)
22 switch(type)
24 case NUMBER:
25 push(atof(s));
26 break;
27 case '+':
28 push(pop() + pop());
29 break;
30 case '*':
31 push(pop() * pop());
32 break;
33 case '-':
34 op2 = pop();
35 push(pop() - op2);
36 break;
37 case '/':
38 op2 = pop();
39 if(op2 != 0.0)
40 push(pop() / op2);
41 else
42 printf("error: zero divisor\n");
43 break;
44 case '%':
45 op2 = pop();
46 if(op2 != 0.0)
48 push((int)(pop()) % (int)(op2));
49 } else {
50 printf("error: zero divisor\n");
52 break;
53 case '\n':
54 printf("\t%.8g\n", pop());
55 break;
56 default:
57 printf("error: unknown command %s\n", s);
58 break;
61 return 0;
64 int sp = 0;
65 double val[MAXVAL];
67 /* push f onto value stack */
68 void push(double f)
70 if(sp < MAXVAL)
71 val[sp++] = f;
72 else
73 printf("error: stack full\n");
77 /* pop and return top value from stack */
78 double pop(void)
80 if(sp > 0)
81 return val[--sp];
82 else
84 printf("error: stack empty\n");
85 return 0.0;
89 int getch(void);
90 void ungetch(int);
92 /* get next operator or numberic operand */
93 int getop(char s[])
95 int i, c;
97 while ((s[0] = c = getch()) == ' ' || c == '\t')
99 s[1] = '\0';
100 if(!isdigit(c) && c != '.')
101 return c;
102 i = 0;
103 if(isdigit(c))
104 while(isdigit(s[++i] = c = getch()))
106 if(c == '.')
107 while(isdigit(s[++i] = c = getch()))
109 s[i] = '\0';
110 if(c != EOF)
111 ungetch(c);
112 return NUMBER;
115 char buf[BUFSIZE];
116 int bufp = 0;
118 int getch(void)
120 return (bufp > 0) ? buf[--bufp] : getchar();
123 void ungetch(int c)
125 if(bufp >= BUFSIZE)
126 printf("ungetch: too many characters\n");
127 else
128 buf[bufp++] = c;