#include <iostream>
#include <cstdio>
#include <stack>
#include <string>
using namespace std;
stack<float> num;//数字栈
stack<char> oper;//运算符栈
bool Calculate(int flag) {
float right = num.top();
num.pop();
float left = num.top();
num.pop();//提取两个数字
oper.pop();
switch (flag) {
case 1://加法
if (oper.size() >= 1) {//减法需要特别处理
(oper.top() == '-') ? num.push(0 - left + right) : num.push(left + right);
oper.pop();//将减法换成加法
oper.push('+');
} else {
num.push(left + right);
}
break;
case 2://减法
if (oper.size() >= 1) {
(oper.top() == '-') ? num.push(0 - left - right) : num.push(left - right);
oper.pop();//将减法换成加法
oper.push('+');
} else {
num.push(left - right);
}
break;
case 3://乘法
num.push(left * right);
break;
case 4://除法
num.push(left / right);//计算后的结果压入数据栈
break;
}
return true;
}
int main() {
char s[201];
while (fgets(s, 201, stdin)) {
string str = s;
if (str == "0\n") {
break;//只有0输入时退出循环
}
for (int i = 0; i < str.size() - 1; i++) {
if ('0' <= str[i] && str[i] <= '9') {
float data = 0;
while ('0' <= str[i] && str[i] <= '9') {
data = data * 10 + str[i] - '0';
i++;
}
num.push(data); //拼接数字并压入数字栈
if (!oper.empty()) {
(oper.top() == '*') ? Calculate(3) : ((oper.top() == '/') ? Calculate(
4) : false);//先计算优先级高的乘除
}
} else if (str[i] == ' ') {
continue;//空格时忽略
} else {
oper.push(str[i]);//压入运算符栈
}
}
while (num.size() != 1 &&
!oper.empty()) { //退出条件为运算符全部使用完毕并且只剩一个结果
if (oper.top() == '+') {
Calculate(1);
} else if (oper.top() == '-') {
Calculate(2);
}
}
printf("%.02f\n", num.top());
num.pop();//清空数据栈,方便下组数据使用
}
}
// 64 位输出请用 printf("%lld")
渣渣思路:乘除应该提前计算,出栈只计算加减时需要考虑将减法结合数字变为加负数

京公网安备 11010502036488号