forked from Heatwave/The-C-Programming-Language-2nd-Edition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
4.reverse-polish-calculator.c
134 lines (116 loc) · 2.28 KB
/
4.reverse-polish-calculator.c
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // for atof()
#include <math.h> // for fmod()
#include "calc.h"
#define MAXOP 100 // max size of operand or operator
#define MAX_VAR_LEN 26 // max size of array for variables
void mathfunc(char[]);
void setVar(double, double);
void getVar(char[]);
double variables[MAX_VAR_LEN];
int variableFlags[MAX_VAR_LEN]; // if [0] is 0, means 'a' not set, if [0] is 1, means 'a' set
// compile with stack.c, getop.c, getch.c
main()
{
int type;
double op2;
char s[MAXOP];
int i;
for (i = 0; i < MAX_VAR_LEN; i++)
variableFlags[i] = 0;
while ((type = getop(s)) != EOF) {
switch(type) {
case NUMBER:
push(atof(s));
break;
case VAR:
getVar(s);
break;
case FUNC:
mathfunc(s);
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
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();
if (op2 == 0.0)
printf("error: can not mod 0\n");
else
push(fmod(pop(), op2));
break;
case '=':
op2 = pop();
setVar(pop(), op2);
break;
case '\n':
printf("\t%.8g\n", pop());
break;
default:
printf("error: unknown command %s\n", s);
break;
}
}
return 0;
}
void mathfunc(char s[])
{
int index;
if (0 == strrindex(s, "sin")) {
push(sin(pop()));
return;
}
if (0 == strrindex(s, "exp")) {
push(exp(pop()));
return;
}
if (0 == strrindex(s, "pow")) {
double ey = pop();
push(pow(pop(), ey));
return;
}
printf("error: unknown func %s\n", s);
return;
}
void setVar(double varIndex, double value)
{
int index = (int)varIndex;
if (index < 0 || index > MAX_VAR_LEN) {
printf("error: cannot set variable, invalid variable: %c\n", index + 'a');
return;
}
variables[index] = value;
variableFlags[index] = 1;
push(value); // to show result
return;
}
void getVar(char s[])
{
if (strlen(s) != 1 && s[0] != 0) {
// if variable is 'a', s[0] == 0, strlen(s) == 0
printf("error: cannot get variable, invalid variable: %s\n", s);
return;
}
double value = atof(s);
int index = (int)value;
if (variableFlags[index] == 0)
push(value);
else
push(variables[index]);
return;
}