/*
* 参考(https://blog.csdn.net/qq_42325947/java/article/details/104219251)
*/
#include <iostream>
#include <stack>
#include <string>
using namespace std;
stack <double> st;
int main()
{
string s;
getline(cin, s);
for (int i = s.size() - 1; i >= 0; i--)
{
if (isdigit(s[i]))
{
double mul = 10, num = s[i] - '0';
for (i--; i >= 0; i--)
{
if (isdigit(s[i]))
{
num += (s[i] - '0') * mul;
mul *= 10;
}
else if (s[i] == '.')
{
num /= mul;
mul = 1;
}
else if (s[i] == '-')
num = -num;
else
break;
}
st.push(num);
}
else if (s[i] != ' ') //else
{
double a, b, sum;
a = st.top();
st.pop();
b = st.top();
st.pop();
switch (s[i])
{
case '+':
sum = a + b;
break;
case '-':
sum = a - b;
break;
case '*':
sum = a * b;
break;
case '/':
{
if (b == 0)
{
cout << "ERROR";
return 0;
}
sum = a / b;
}
}
st.push(sum);
}
}
printf("%.1lf", st.top());
}
其中用到了getline 函数以及isdigit 函数。 整个思路是从后向前遍历整个字符串,遇到符号直接运算即可,不用cin 是因为cin遇到空格会结束。
参考
https://blog.csdn.net/qq_42325947/java/article/details/104219251