Ruby 总是围捕

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25542681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:33:49  来源:igfitidea点击:

Ruby Always Round Up

ruby

提问by Brandon

I feel like a crazy person. I'd like to round all fractions up to the nearest whole number.

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

For example, 67/30 = 2.233333333334. I would like to round that up to 3. If the result is not a whole number, I never want to round down, only up.

例如,67/30 = 2.233333333334。我想把它四舍五入到 3。如果结果不是整数,我从不想向下舍入,只想向上舍入。

This is what I'm trying:

这就是我正在尝试的:

puts 67/30.to_f.ceil

Here are examples of what I'm looking for:

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

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

Any ideas? Thanks much!

有任何想法吗?非常感谢!

回答by fivedigit

The problem is that you're currently calling ceilon 30.to_f. Here's how Ruby evaluates it:

问题是,你现在叫ceil30.to_f。以下是 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

To solve this, you can just add parenthesis:

要解决这个问题,您只需添加括号:

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