-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix.c
More file actions
59 lines (56 loc) · 1.03 KB
/
postfix.c
File metadata and controls
59 lines (56 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "ccalc.h"
#include <math.h>
int eval_postfix(char *s)
{
stack stk;
scanner sc;
stk_init(&stk);
scnr_init(&sc, s);
while (scnr_hasnext(sc))
{
if (1 == scnr_hasnextint(sc))
stk_push(&stk, scnr_nextint(&sc));
else
{
int op1, op2;
switch (scnr_next(&sc))
{
case '+':
op2 = stk_pop(&stk);
op1 = stk_pop(&stk);
stk_push(&stk, op1+op2);
break;
case '-':
op2 = stk_pop(&stk);
op1 = stk_pop(&stk);
stk_push(&stk, op1-op2);
break;
case '*':
op2 = stk_pop(&stk);
op1 = stk_pop(&stk);
stk_push(&stk, op1 * op2);
break;
case '/':
op2 = stk_pop(&stk);
op1 = stk_pop(&stk);
if (0 == op2)
printf("postfix: divide by 0\n");
else
stk_push(&stk, op1 / op2);
break;
case '%':
op2 = stk_pop(&stk);
op1 = stk_pop(&stk);
stk_push(&stk, op1 % op2);
break;
case '^':
op2 = stk_pop(&stk);
op1 = stk_pop(&stk);
stk_push(&stk, (int) pow((double)op1,
(double)op2));
break;
}
}
}
return stk_pop(&stk);
}