Top

表达式求值(逆波兰)


博主CSDN

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

#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e3 + 10;
typedef long long ll;
char s[maxn];
int cmp(char ch){
switch (ch){
case '+':
case '-':return 1;
case '*':
case '/':return 2;
default:return 0;
}
}
string ss = "";
void ToSuffix(){
stack<char>Se;
double ans = 0;
Se.push('#');
int len = strlen(s);
for (int i = 0; i<len; i++){
if (s[i] >= '0'&&s[i] <= '9'){
ss += s[i++];
while (s[i] >= '0'&&s[i] <= '9'){
ss += s[i++];
}
ss += ' ';
}
if (s[i] == '(')Se.push(s[i]);
else if (s[i] == ')'){
while (Se.top() != '('){
ss += Se.top();
ss += ' ';
Se.pop();
}
Se.pop();
}
else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/'){
while (cmp(Se.top()) >= cmp(s[i])){
ss += Se.top();
ss += ' ';
Se.pop();
}
Se.push(s[i]);
}
}
while (Se.top() != '#'){
ss += Se.top();
ss += ' ';
Se.pop();
}
Se.pop();
}
double Solve(){
stack<double>num;
int i = 0;
double x = 0, y = 0,ans=0;
for (int i = 0; ss[i]; i++){
if (ss[i] >= '0'&&ss[i] <= '9'){
ans = ss[i++] - '0';
while (ss[i] >= '0'&&ss[i] <= '9'){
ans =ans*10+ ss[i++]-'0';
}
num.push(ans);
ans = 0;
}
else if (ss[i] == ' ');
else{
x = num.top();
num.pop();
y = num.top();
num.pop();
if (ss[i] == '+')num.push(x + y);
else if (ss[i] == '-')num.push(y - x);
else if (ss[i] == '*')num.push(x * y);
else if (ss[i] == '/')num.push(y / x);
}
}
x = num.top();
num.pop();
return x;
}
int main(){
freopen("C:/Users/Administrator/Desktop/input.txt", "r", stdin);
int t;
scanf("%d", &t);
while (t--){
scanf("%s", s);
ss = "";
ToSuffix();
printf("%.2f\n",Solve());
}
return 0;
}



未经允许不得转载: Anoyer's Blog » 表达式求值(逆波兰)