blob: cb484ad53aa69a0303ff4cde06894478b5e8d4c2 (
plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAXOP 100
#define NUMBER '0'
int getop(char[]);
void push(double);
double pop(void);
double peek();
void ungets();
int
main()
{
int type, var;
double op1, op2, r;
char s[MAXOP];
char v[26];
/* reverse Polish calculator */
while ((type = getop(s)) != EOF) {
switch (type) {
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
/* to guarantee the right order, the first value must be stored */
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 '%':
op2 = pop();
op1 = pop();
if (op1 >= 0.0 && op2 >= 0.0) {
push((int)op1 % (int)op2);
} else if (op1 < 0.0 || op2 < 0.0) {
push(0);
} else {
printf("error: zero divisor\n");
}
break;
/* print without popping */
case 'p':
printf("%f\n", peek());
break;
/* duplicate */
case 'd':
op2 = peek();
push(op2);
break;
/* swap top two elements */
case 's':
op2 = pop();
op1 = pop();
push(op2);
push(op1);
break;
case '=':
pop();
if (var > 'a' && var < 'z') {
v[var - 'a'] = pop();
}
case '\n':
r = pop();
printf("\t%.8g\n", r);
break;
case 'u':
ungets();
break;
default:
if (type == 'R') {
push(r);
} else if (type >= 'a' && type <= 'z') {
push(v[type - 'a']);
} else {
printf("error: unknown command %s\n", s);
}
break;
}
var = type;
}
return 0;
}
|