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

Java数组遍历计算总重量逻辑错误排查求助

Java商品总重量计算逻辑错误修复

错误原因

你的代码核心问题出在第20行:

totalWeight = weight;

这行代码是直接将当前商品的重量赋值给总重量,而非累加。每次循环都会覆盖之前计算的总重量,最终函数只会返回数组最后一个元素的重量(也就是测试用例里的21.0),完全不符合“计算所有商品总重量”的需求。

解决思路

把赋值操作改成累加操作,让每个商品经过折扣处理后的重量都被加到总重量中,替换为:

totalWeight += weight;

修正后的代码

float calculateWeight(float[] weights, boolean hasLoyaltyCard) {
    float totalWeight = 0;
//
    for (int i = 0; i < weights.length; i++) { // (for) loop the array
        float weight = weights[i];             // float var with looped array returns
        if (weight < 20f && hasLoyaltyCard) {  // check for under 20oz AND boolean
            weight *= 0.95f;                   // if true, multiply weight by 5% & update
        } 
        totalWeight += weight;                 // 累加处理后的商品重量到总重量
    }    
//
    return totalWeight;
}

验证测试用例

  • 当输入数组[19f,20f,21f]且无会员卡时,总重量为19+20+21=60.0,匹配第一个测试用例的期望结果。
  • 当有会员卡时,19oz的商品打5%折后为19*0.95=18.05,总重量为18.05+20+21=59.05,匹配第二个测试用例的期望结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:20:21