题面:
波兰表达式是一种把运算符前置的算术表达式,例如普通的表达式2 + 3的波兰表示法为+ 2 3。波兰表达式的优点是运算符之间不必有优先级关系,也不必用括号改变运算次序,例如(2 + 3) * 4的波兰表示法为* + 2 3 4。本题求解波兰表达式的值,其中运算符包括+ - * /四个
输入为一行,其中运算符和运算数之间都用空格分隔,运算数是浮点数。
输出为一行,表达式的值。
* + 11.0 12.0 + 24.0 35.0
1357.000000
可直接用printf("%f\n", v)输出表达式的值v。
可使用atof(str)把字符串转换为一个double类型的浮点数。atof定义在math.h中。
代码:
#include <bits/stdc++.h>
using namespace std;
string s;
stack <double> st;
stack <string> stt;
int main () {
while (cin >> s) {
double sum = 0;
for (int i = 0; i < s.size (); i ++)
if (s[i] >= '0' && s[i] <= '9') {
sum = stod (s);
break;
}
if (sum) st.push (sum);
else stt.push (s);
}
while (! stt.empty ()) {
double x = st.top (); st.pop (); double y = st.top (); st.pop ();
if (stt.top () == "*") {
st.push (x * y); stt.pop (); continue;
}
if (stt.top () == "+") {
st.push (x + y); stt.pop (); continue;
}
if (stt.top () == "-") {
st.push (y - x); stt.pop (); continue;
}
if (stt.top () == "/") {
st.push (y / x); stt.pop (); continue;
}
}
printf ("%lf", st.top ());
}