题目描述
输入一个逆波兰式 ,又称后缀表达式(将运算符写在操作数之后)计算出它的值。保证数据合法,不会出现除0的情况,输入的数字都是整数
输入
一个逆波兰式
输出
值 计算结果保留2位小数
样例输入
1 2 + 3 4 + *
样例输出
21.00
题解
#include<bits/stdc++.h>
using namespace std;
int main() {
stack<double> S;
string x;
while (cin >> x) {
istringstream iss(x);
double r;
if (iss >> r)
S.push(r);
else {
double second = S.top();
S.pop();
double first = S.top();
S.pop();
double res = first;
if (x[0] == '+') {
res += second;
} else if (x[0] == '-') {
res -= second;
} else if (x[0] == '*') {
res *= second;
} else {
res /= second;
}
S.push(res);
}
}
cout << fixed << setprecision(2) << S.top() << endl;
return 0;
}