E24588: 后序表达式求值
Stack, http://cs101.openjudge.cn/practice/24588/
思路:按照课上讲的用栈解决即可,忘记处理单走一个数字的情形了,花了点时间找bug,用时约20min,由于代码全部手敲,因此运行时间很短,仅1ms
cpp
#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>
using namespace std;
vector<double> st;
bool isNumber(char s)
{
return (s >= '0' && s <= '9');
}
void calc(char c)
{
double a = st.back(); st.pop_back();
double b = st.back(); st.pop_back();
switch (c)
{
case '+': st.push_back(b + a); break;
case '-': st.push_back(b - a); break;
case '*': st.push_back(b * a); break;
case '/': st.push_back(b / a); break;
}
}
double calculate()
{
st.clear();
char c;
double tmp = 0;
bool isNum = false;
double frac = 0;
while ((c = getchar()))
{
if (c == '\n' || c == EOF)
{
if (isNum) st.push_back(tmp);
break;
}
if (isNumber(c))
{
isNum = true;
if (frac == 0) tmp = tmp * 10 + (c - '0');
else
{
tmp += (c - '0') * frac;
frac *= 0.1;
}
}
else if (c == '.')
{
frac = 0.1;
}
else if (c == ' ')
{
if (isNum)
{
st.push_back(tmp);
tmp = 0; frac = 0; isNum = false;
}
}
else if (c == '+' || c == '-' || c == '*' || c == '/')
{
if (isNum)
{
st.push_back(tmp);
tmp = 0; frac = 0; isNum = false;
}
calc(c);
}
}
return st.back();
}
int main()
{
int N;
cin >> N;
cin.ignore();
while (N--)
{
double ans = calculate();
cout << fixed << setprecision(2) << ans << endl;
}
}