You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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-/+"会按照实际数字值计算:

  1. 处理3 1 2 * +得到3 + (1*2) = 5
  2. 处理4 5 6 * +得到4 + (5*6) = 34,叠加后为5+34=39
  3. 处理9 7 -得到9-7=2,再与39做除法得到39/2=19.5
  4. 最后执行加法(表达式末尾的+需对应前序结果与另一操作数,若输入表达式无遗漏,最终结果会符合预期逻辑)

内容的提问来源于stack exchange,提问作者ian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:31:35