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

Ruby初学者if/else编程问题:speed=10时测试失败返回27而非预期28

问题原因

核心问题是你代码触发了Ruby默认整数除法规则,计算顺序错误导致精度过早被截断:

  • 你的代码先执行 @speed * 221 / 60 做整数运算,当speed为10时,10*221=2210,整数除法2210/60会直接舍弃小数部分得到36(实际浮点值为36.8333...)
  • 后续乘0.77得到36*0.77=27.72,向下取整后得到27,和预期不符

正确的计算逻辑应该是先算完整的每小时合格产量,再换算为分钟产量,全程保留浮点精度直到最后取整。

修复后的代码

class AssemblyLine
  def initialize(speed)
    @speed = speed
  end

  def working_items_per_minute
    # 用221.0触发浮点运算,避免整数除法丢失精度
    hourly_total = @speed * 221.0
    rate = case @speed
           when 1..4 then 1
           when 5..8 then 0.9
           when 9 then 0.8
           else 0.77
           end
    (hourly_total * rate / 60).floor
  end
end

验证计算

当speed为10时:
10 * 221.0 * 0.77 / 60 = 28.361666...,向下取整后得到28,符合测试预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:27:03