-
Notifications
You must be signed in to change notification settings - Fork 0
/
Postfix
127 lines (122 loc) · 3.29 KB
/
Postfix
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
#include <stdio.h>
#include <stdlib.h>
typedef double ElementType;
#define Infinity 1e8
#define Max_Expr 30 // max size of expression
ElementType EvalPostfix( char *expr );
int main()
{
ElementType v;
char expr[Max_Expr];
gets(expr);
v = EvalPostfix( expr );
if ( v < Infinity )
printf("%f\n", v);
else
printf("ERROR\n");
return 0;
}
ElementType EvalPostfix( char *expr )
{
int i;
ElementType stack[Max_Expr] = {0};
int n = 0;
int sign = 1;
int PositiveExponent = 1;
double NegativeExponent = 0.1;
int decimal = 0;
ElementType push = 0;
for(i = 0; i < Max_Expr; i++)
{
if (expr[i] == 0)break;
switch(expr[i])
{
case ' ':
break;
case '+':
{
if(n < 2)return Infinity;
n -= 2;
stack[n] = stack[n] + stack[n+1];
stack[n+1] = 0;
//printf("+push:%lf\n",stack[n]);
n++;
break;
}
case '-':
{
if(expr[i+1] == ' '||expr[i+1] == 0)
{
if(n < 2)return Infinity;
n -= 2;
stack[n] = stack[n] - stack[n+1];
stack[n+1] = 0;
//printf("-push:%lf\n",stack[n]);
n++;
}
else
{
sign = -1;
}
break;
}
case '*':
{
if(n < 2)return Infinity;
n -= 2;
stack[n] = stack[n] * stack[n+1];
stack[n+1] = 0;
//printf("*push:%lf\n",stack[n]);
n++;
break;
}
case '/':
{
if(n < 2)return Infinity;
n -= 2;
if(stack[n+1] == 0)return Infinity;
stack[n] = stack[n] / stack[n+1];
stack[n+1] = 0;
//printf("/push:%lf\n",stack[n]);
n++;
break;
}
default:
{
push = 0;
PositiveExponent = 1;
NegativeExponent = 0.1;
while(expr[i] >= '0' && expr[i] <= '9' || expr[i] == '.')
{
if(expr[i] == '.')
{
decimal = 1;
i++;
continue;
}
if(decimal)
{
push = push + (expr[i] - '0')* NegativeExponent;
NegativeExponent *= 0.1;
i++;
}
else
{
push = push * PositiveExponent + expr[i] - '0';
PositiveExponent = 10;
i++;
}
}
stack[n] = push * sign;
//printf("readpush:%lf\n",stack[n]);
n++;
sign = 1;
decimal = 0;
i--;
}
}
}
if(stack[1] != 0)
return Infinity;
else return stack[0];
}