-
Notifications
You must be signed in to change notification settings - Fork 3
/
5-10.c
74 lines (66 loc) · 1.66 KB
/
5-10.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
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
int stack_index = 0;
double stack[MAX_STACK_SIZE];
void error(const char *msg) {
fprintf(stderr, "%s\n", msg);
exit(EXIT_FAILURE);
}
// Function for pushing into stack
void push(double new_stack_number) {
if (stack_index < MAX_STACK_SIZE)
stack[stack_index++] = new_stack_number;
else
error("Error : Stack full\n");
}
// Function for poping from stack
double pop() {
if (stack_index > 0)
return stack[--stack_index];
else {
error("Error : Stack empty\n");
return 0;
}
}
int main(int argc, char **argv) {
int temp = 0;
for (int arg_index = 1; arg_index < argc; arg_index++)
switch (argv[arg_index][0]) {
case '\0':
error("Empty command line argument");
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
push(atof(argv[arg_index]));
break;
case '+':
push(pop() + pop());
break;
case '-':
temp = pop();
push(pop() - temp);
break;
case 'x':
push(pop() * pop());
break;
case '/':
temp = pop();
push(pop() / temp);
break;
default:
error("Unknown operator");
break;
}
printf("%g\n", pop());
return 0;
}