Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_4.4_rpn_top_two_elements.c
1240 views
1
/* Add commands to
2
- print top element of the stack,without poping
3
- duplicate it
4
- swap the top two elements
5
- Clear the stack */
6
7
#include<stdio.h>
8
#include<stdlib.h>
9
#include<math.h>
10
11
#define MAXOP 100
12
#define NUMBER '0'
13
14
int getop(char []);
15
void push(double);
16
double pop(void);
17
18
/* reverse polish calculator */
19
20
int main(void)
21
{
22
int type;
23
double op2,op1;
24
char s[MAXOP];
25
void clearsp(void);
26
27
while((type = getop(s)) != EOF)
28
{
29
switch(type)
30
{
31
case NUMBER:
32
push(atof(s));
33
break;
34
case '+':
35
push(pop()+pop());
36
break;
37
case '*':
38
push(pop()*pop());
39
break;
40
case '-':
41
op2 = pop();
42
push(pop()-op2);
43
break;
44
case '/':
45
op2 = pop();
46
if(op2 != 0.0)
47
push(pop()/op2);
48
else
49
printf("error:zero divisor\n");
50
break;
51
case '%':
52
op2 = pop();
53
if(op2 != 0.0)
54
push(fmod(pop(),op2));
55
else
56
printf("erro:zero divisor\n");
57
break;
58
case '?':
59
op2=pop();
60
printf("\t%.8g\n",op2);
61
push(op2);
62
break;
63
case 'c':
64
clearsp();
65
break;
66
case 'd':
67
op2=pop();
68
push(op2);
69
push(op2);
70
break;
71
case 's':
72
op1=pop();
73
op2=pop();
74
push(op1);
75
push(op2);
76
break;
77
case '\n':
78
printf("\t%.8g\n",pop());
79
break;
80
default:
81
printf("error: unknown command %s\n",s);
82
break;
83
}
84
}
85
return 0;
86
}
87
88
89
#define MAXVAL 100
90
91
int sp = 0;
92
double val[MAXVAL];
93
94
void push(double f)
95
{
96
if(sp < MAXVAL)
97
val[sp++]=f;
98
else
99
printf("error:stack full, cant push %g\n",f);
100
}
101
102
103
double pop(void)
104
{
105
if(sp>0)
106
return val[--sp];
107
else
108
{
109
printf("error: stack empty\n");
110
return 0.0;
111
}
112
}
113
114
void clearsp(void)
115
{
116
sp = 0;
117
}
118
119
#include<ctype.h>
120
121
int getch(void);
122
void ungetch(int);
123
124
int getop(char s[])
125
{
126
int i,c;
127
128
while((s[0] = c = getch()) == ' ' || c =='\t')
129
;
130
s[1] = '\0';
131
132
i = 0;
133
if(!isdigit(c) && c!='.' && c!='-')
134
return c;
135
136
if(c=='-')
137
if(isdigit(c=getch()) || c == '.')
138
s[++i]=c;
139
else
140
{
141
if(c!=EOF)
142
ungetch(c);
143
return '-';
144
}
145
146
if(isdigit(c))
147
while(isdigit(s[++i] =c =getch()))
148
;
149
150
if(c=='.')
151
while(isdigit(s[++i] = c=getch()))
152
;
153
154
s[i] = '\0';
155
if(c!=EOF)
156
ungetch(c);
157
return NUMBER;
158
}
159
160
#define BUFSIZE 100
161
162
char buf[BUFSIZE];
163
int bufp = 0;
164
165
int getch(void)
166
{
167
return (bufp > 0) ? buf[--bufp] : getchar();
168
}
169
170
void ungetch(int c)
171
{
172
if(bufp >= BUFSIZE)
173
printf("ungetch: too many characters\n");
174
else
175
buf[bufp++] = c;
176
}
177
178
179