gpt4 book ai didi

Ruby 总是四舍五入

转载 作者:数据小太阳 更新时间:2023-10-29 06:20:58 25 4
gpt4 key购买 nike

我觉得自己像个疯子。我想将所有分数四舍五入到最接近的整数。

例如,67/30 = 2.233333333334。我想将其四舍五入为 3。如果结果不是整数,我不想向下舍入,只会向上舍入。

这就是我正在尝试的:

puts 67/30.to_f.ceil

以下是我正在寻找的示例:

  • 67/30 = 3
  • 50/100 = 1
  • 2/2 = 1

有什么想法吗?非常感谢!

最佳答案

问题是您当前正在 30.to_f 上调用 ceil。以下是 Ruby 对其求值的方式:

(67)/(30.to_f.ceil)
# .ceil turns the float into an integer again
(67)/(30.0.ceil)
# and now it's just an integer division, which will be 2
67/30 # = 2

要解决这个问题,您可以添加括号:

puts (67/30.to_f).ceil  # = 3

关于Ruby 总是四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25542681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com