pol.c
c
1#include<stdio.h>
2#include <ctype.h>
3
4#define ERR_VAL (-9999999)
5
6int stack[100];
7int stack_point = 0;
8int has_error = 0;
9
10void clear() {
11 stack_point = 0;
12}
13
14int pop() {
15 if (stack_point == 0) {
16 printf("#--- stack under flow");
17 has_error++;
18 }
19 return stack[--stack_point];
20}
21
22void push(int v) {
23 if (100 <= stack_point) {
24 printf("#--- stack overflow");
25 has_error++;
26 return;
27 }
28 stack[stack_point++] = v;
29 return ;
30}
31
32int calc(const char * exp) {
33 int val, a, b;
34
35 while (*exp && has_error == 0) {
36 char c = *exp;
37 exp++;
38
39 switch (c) {
40 case '0':
41 case '1':
42 case '2':
43 case '3':
44 case '4':
45 case '5':
46 case '6':
47 case '7':
48 case '8':
49 case '9':
50 val = (int)c - (int)'0';
51 while (1) {
52 if (isdigit(*exp)) {
53 char c_next = *exp;
54 exp++;
55 val = val * 10 + ((int)c_next - (int)'0');
56 } else {
57 break;
58 }
59 }
60 push(val);
61 break;
62 case '+':
63 push(pop() + pop());
64 break;
65 case '-':
66 push(pop() - pop());
67 break;
68 case '*':
69 push(pop() * pop());
70 break;
71 case '/':
72 a = pop();
73 b = pop();
74 if (b == 0) {
75 printf("#--- divide by 0");
76 has_error++;
77 }
78 push(b / a);
79 break;
80 case ' ':
81 break;
82 default:
83 printf("存在しない演算子");
84 has_error++;
85 break;
86 }
87 }
88
89 if (has_error != 0) {
90 return ERR_VAL;
91 }
92 return pop();
93}
94
95int main() {
96 // char * exp = "23 109 + 15 + 7* 117 13 14 *+ + 11 27 29 53 + + + + 27 16 *+ 136 +";
97 const char * exps[] =
98 {
99 "1",
100 "12345",
101 "2 3 +",
102 "2 3+",
103 "2 3 -",
104 "2 3 *",
105 "10 3 /",
106 "2 3 +",
107 "2 3 4 + *",
108 "2 3 4+*",
109 "23 109 + 15 + 7* 117 13 14 *+ + 11 27 29 53 + + + + 27 16 *+ 136 +"
110 };
111
112 for (int i = 0; i < sizeof(exps) / sizeof(char**); i++) {
113 int n = calc(exps[i]);
114 if (has_error == 0) {
115 printf("%s => %d\n", exps[i], n);
116 }
117 }
118 return 0;
119}
実行例
追記/訂正
"-" の処理部が間違ってました!。(コメントで指摘されている)
c
1 case '-':
2 a = pop();
3 b = pop();
4 push(b - a);
5 break;
とすれば、 "2 3 -" は -1 計算されます。