简单的中缀表达式转后缀及计算
Tamako

c++版本

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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#include <iostream>
#include <string>
#include <stack>
#include <vector>

using namespace std;
int pri(char x)
{
if(x=='/' || x=='*')
return 2;
if(x=='+' || x=='-')
return 1;
if(x=='(')
return 0;
else
return -1;
}
vector<string> in_to_post(string input)
{
stack<char> s;
vector<string> post;
string t="";
int i=0;
while(input[i])
{
char tmp = (char)input[i];
if(tmp >= '0' && tmp <= '9')
{

string num_tmp;
int j = i;
while((tmp >= '0' && tmp <= '9') || tmp == '.')
{
num_tmp += tmp;
tmp = (char)input[++j];
}
post.push_back(num_tmp);
i = j-1;
}
else
{

if(s.empty())
{
s.push(tmp);
}
else if(tmp=='(')
{
s.push(tmp);
}
else if(tmp==')')
{
while(s.top()!='(')
{
t = "";
t += s.top();
post.push_back(t);
s.pop();
}
s.pop();
}
else
{
while(pri(tmp)<=pri(s.top()))
{
t = "";
t += s.top();
post.push_back(t);
s.pop();
if(s.empty())
break;
}
s.push(tmp);
}
}
i++;
}
if(!s.empty())
{
t = "";
t += s.top();
post.push_back(t);
s.pop();
}
return post;
}
double cal(double a,double b,char c)
{
if(c=='+')
return a+b;
else if(c=='-')
return a-b;
else if(c=='*')
return a*b;
else if(c=='/')
return a/b;
else
return 0;
}
int myisdigit(string s)
{
int i=0;
while(i<s.size())
{
if(s[i]!='.'&&(s[i]<'0'||s[i]>'9'))
return 0;
i++;
}
return 1;
}
double postcal(vector<string> in)
{
stack<string> s;
int i=0;
while(i<in.size())
{
string tmp = in[i];
if(myisdigit(tmp))
{
s.push(tmp);
}
else
{
double b = stod(s.top());
s.pop();
double a= stod(s.top());
s.pop();
char c = tmp[0];
double r = cal(a,b,c);
s.push(to_string(r));
}
i++;
}
return stod(s.top());
}
int main()
{
string input;
int i=0;
vector<string> postinput;
cout<<"请输入中缀表达式:"<<endl;
cin>>input;

postinput=in_to_post(input);
cout<<"后缀表达式为:"<<endl;
for(i=0; i<postinput.size(); i++)
{
cout<<postinput[i]<<" ";
}

double res = postcal(postinput);

cout<<endl<<"结果为:"<<res<<endl;

return 0;
}
/*
请输入中缀表达式:
1.2*((2/4.3)*3.2)
后缀表达式为:
1.2 2 4.3 / 3.2 * *
结果为:1.78605

to_string stod均为c++11特性,需编译器支持,
in codeblocks,go to settings->compiler->check the "have g++ follow the c++11 ISO..."
*/