-
Notifications
You must be signed in to change notification settings - Fork 1
/
表达式求值递归.cpp
112 lines (104 loc) · 1.76 KB
/
表达式求值递归.cpp
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
#include<iostream>
#include<cstdlib>
#include<string>
#include<stack>
using namespace std;
char orig[200];
int step = 0;
int main()
{
double solve();
cin >> orig;
cout << solve();
system("PAUSE");
return 0;
}
double solve()
{
stack<double> res;
stack<char> ope;
void getnum(stack<double> &res);
int weight(char oper);
double cal(double a, double b, char oper);
ope.push(0);
if (orig[step] == '-')
{
res.push(-1);
ope.push('*');
step++;
}
while (1)
{
getnum(res);
while (1)
{
if (res.size() == 1 && (orig[step] == '\0' || orig[step] == ')'))
{
step++;
return res.top();
}
if (orig[step] == '(')
{
step++;
res.push(solve());
}
else if (orig[step] == ')' || orig[step] == '\0')
{
double a, b;
a = res.top(); res.pop();
b = res.top(); res.pop();
res.push(cal(b, a, ope.top()));
ope.pop();
}
else if (weight(ope.top()) >= weight(orig[step]))
{
double a, b;
a = res.top(); res.pop();
b = res.top(); res.pop();
res.push(cal(b, a, ope.top()));
ope.pop();
ope.push(orig[step]);
step++;
break;
}
else if (weight(ope.top()) < weight(orig[step]))
{
ope.push(orig[step]);
step++;
break;
}
}
}
}
void getnum( stack<double> &res)
{
for (string num; orig[step] >= '0' && orig[step] <= '9'; step++)
{
num += orig[step];
if (orig[step + 1]<'0' || orig[step + 1]>'9')
{
step++;
res.push(atoi(num.c_str()));
break;
}
}
}
double cal(double a, double b, char oper)
{
switch (oper)
{
case '+':return a + b;
case '-':return a - b;
case '*':return a * b;
case '/':return a / b;
}
}
int weight(char oper)
{
if (oper == '+' || oper == '-')
return 1;
else if (oper == '*' || oper == '/')
return 2;
else if (oper == 0)
return 0;
}