Java栈实现后缀表达式求值结果异常,请求排查问题
后缀表达式求值错误分析与修复
你的代码核心错误在于字符转数字的方式错误,导致栈中存储的是字符的ASCII码而非实际数字值,这直接引发计算结果严重偏离预期。
关键问题点
- 字符转数值逻辑错误:你使用
(float)token将字符转成浮点数,比如字符'3'的ASCII码是51,栈中存储的是51.0而非3.0。所有数字操作数都被错误替换为对应的ASCII值,最终计算结果完全失真。 - 注:你的
calculate方法参数传递和运算逻辑是正确的,弹出顺序与运算顺序匹配后缀表达式规则。
修复后的代码
import java.util.Stack; public class PostFixEvaluate { public static float calculate(Float operand_1, char operator, Float operand_2) { switch (operator) { case '+': return operand_2 + operand_1; case '-': return operand_2 - operand_1; case '*': return operand_2 * operand_1; case '/': return operand_2 / operand_1; } return 0; } public static float postFixEvaluation(String expr) { Stack<Float> stack = new Stack<>(); int index = 0; while (index < expr.length()) { char token = expr.charAt(index); boolean isOperand = isOperand(token); if (isOperand) { // 修复:通过字符差值获取实际数字值 float operandIn = token - '0'; stack.push(operandIn); } else { float a = stack.pop(); float b = stack.pop(); stack.push(calculate(a, token, b)); } index += 1; } return stack.pop(); } public static boolean isOperand(char c) { switch (c) { case '+': case '-': case '*': case '/': return false; default: return true; } } }
验证说明
修复后,输入表达式"312*+456*+97-/+"会按照实际数字值计算:
- 处理
3 1 2 * +得到3 + (1*2) = 5 - 处理
4 5 6 * +得到4 + (5*6) = 34,叠加后为5+34=39 - 处理
9 7 -得到9-7=2,再与39做除法得到39/2=19.5 - 最后执行加法(表达式末尾的
+需对应前序结果与另一操作数,若输入表达式无遗漏,最终结果会符合预期逻辑)
内容的提问来源于stack exchange,提问作者ian
相关产品推荐
相关产品推荐

