-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path正整数表达式求值非递归.cpp
116 lines (106 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
112
113
114
115
#include<iostream>
#include<cstdlib>
#include<string>
#include<stack>
using namespace std;
int main()
{
char orig[200];
stack<double> res;
stack<char> ope;
cin >> orig;
int flagsmall = 1;
int flagbig = 1;
ope.push(0);
for (int i = 0; flagbig ; i++)
{
for (string num;orig[i]>='0' && orig[i]<='9';i++)
{
num += orig[i];
if (orig[i + 1]<'0' || orig[i + 1]>'9')
{
i++;
res.push(atoi(num.c_str()));
break;
}
}
double cal(double a, double b, char oper);
int opeJudg(char ope1, char ope2);
while (1)
{
if (orig[i] == 0 && res.size() == 1)
{
flagbig = 0;
break;
}
if (opeJudg(ope.top(),orig[i])==-1)
{
ope.push(orig[i]);
break;
}
else if (opeJudg(ope.top(), orig[i]) ==0)
{
ope.pop();
break;
}
else if (opeJudg(ope.top(), orig[i]) == 1)
{
double a, b;
a = res.top(); res.pop();
b = res.top(); res.pop();
res.push(cal(b, a, ope.top()));
ope.pop();
}
}
}
cout << res.top();
system("PAUSE");
return 0;
}
int opeJudg(char ope1,char ope2)
{
if (ope1 == '+' || ope1 == '-')
{
if (ope2 == '+' || ope2 == '-' || ope2== ')' || ope2=='\0')
return 1;
if (ope2 == '*' || ope2 == '/' || ope2 == '(')
return -1;
}
if (ope1 == '*' || ope1 == '/')
{
if (ope2 == '+' || ope2 == '-' || ope2 == ')' || ope2 == '\0')
return 1;
if (ope2 == '*' || ope2 == '/')
return 1;
if (ope2 == '(')
return -1;
}
if (ope1 == '(')
{
if (ope2 == ')')
return 0;
else
return -1;
}
if (ope1 == ')')
{
return 1;
}
if (ope1 == 0)
{
if (ope2 == 0)
return 0;
else
return -1;
}
}
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;
}
}