#include <iostream> #include <stack> #include <cctype> using namespace std; int _priority(char c) { if (c == '+' || c == '-') return 1; else return 2; } bool _isOp(char c) { if (c == '+' || c == '-' || c == '*' || c == '/') return true; return false; } float _calculate(float a, float b, char op) { if (op == '+') return a + b; else if (op == '-') return a - b; else if (op == '*') return a * b; else return a / b; } int main() { string str; while (getline(cin, str)) { if (str == "0") break; stack<float> nums; stack<char> ops; for (int i = 0; i < str.size(); i++) { if (str[i] == ' ') continue; else if (isdigit(str[i])) { // 处理数字/多位数 float temp = 0; // ***********************************************i++会越界访问数组!!!! //while (isdigit(str[i])) { while (i<str.size() && isdigit(str[i])) {//*******************先越界检查再判断,次序别反了!!! temp = temp * 10 + ( str[i] - '0' ); i++; } // 结束的时候i不是数字,走过了,需要退回 i--; // 数字直接入栈就可以,只有操作符入栈才涉及运算 nums.push(temp); } else if(_isOp(str[i])) { // 处理运算符 // 高入低弹 (<=都弹,弹完入) //************************************************if (ops.empty()) ops.push(str[i]); if (ops.empty()) { ops.push(str[i]); continue; } // ops非空 if (_priority(str[i]) > _priority(ops.top())) ops.push(str[i]); else { // <= //******************************************************先越界检查再判断,次序别反了!!! while (!ops.empty() && _priority(str[i]) <= _priority(ops.top())) { // 运算 注意操作数次序关系,运算后入操作数栈 float temp_res, a, b; char op; b = nums.top(); nums.pop(); a = nums.top(); nums.pop(); op = ops.top(); ops.pop(); temp_res = _calculate(a, b, op); nums.push(temp_res); } // 运算后 入 ops.push(str[i]); } } } // 遍历一遍str结束 最后ops内优先级要么相同要么从低到高,顺序计算即可 while (!ops.empty()) { float temp_res, a, b; char op; b = nums.top(); nums.pop(); a = nums.top(); nums.pop(); op = ops.top(); ops.pop(); temp_res = _calculate(a, b, op); nums.push(temp_res); } // 运算后nums仅剩一个结果值 printf("%.2f\n", nums.top()); } } // 64 位输出请用 printf("%lld")