ruby 红宝石 .ceil 和 .floor
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39971830/
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
Ruby .ceil and .floor
提问by misokuan
I'm new to Ruby and I'm trying to figure out how ceiland floorworks as I get different answers when a fraction or a decimal number is used (similar value). Below is what I have tried:
我是新来的Ruby和我试图找出如何ceil和floor作品,我得到不同的答案时,分数或十进制数,使用(类似于值)。以下是我尝试过的:
puts 8/3.ceil == 2 #=> true
puts 8/3.floor == 2 #=> true
puts 2.67.ceil == 2 #=> false
puts 2.67.floor == 2 #=> true
From my understanding, ceilshould return a number higher and flooris a number lower. Hope someone can enlighten me on this. Thank you! :)
根据我的理解,ceil应该返回一个更高的数字并且floor是一个更低的数字。希望有人能在这方面启发我。谢谢!:)
回答by Andrey Deineko
Everything is returned correctly.
一切都正确返回。
puts 8/3.ceil == 2
#=> true, because 8/3 returns an Integer, 2
puts 8/3.floor == 2
#=> true, because 8/3 returns an Integer, 2
puts 2.67.ceil == 2
#=> false, because 2.67.ceil is 3
puts 2.67.floor == 2
#=> true, because 2.67.floor is 2
To make things of more sense here, you can convert results to Float:
为了使这里更有意义,您可以将结果转换为浮点数:
(8.to_f / 3).ceil == 2 #=> false
(8.to_f / 3).floor == 2 #=> true
2.67.ceil == 2 #=> false
2.67.floor == 2 #=> true
Another thing to bear in mind, that having written 8/3.ceilis actually 8 / (3.ceil), because the .binds stronger than /. (thx @tadman)
另一件要记住的事情,写了8/3.ceil实际上是8 / (3.ceil),因为.绑定比/. (感谢@tadman)
Yet another thing to mention, is that (thx @Stefan):
还有一件事要提到的是(感谢@Stefan):
There's also
fdivto perform floating point division, i.e.8.fdiv(3).ceil. And Ruby also comes with a niceRationalclass:(8/3r).ceil.
还有
fdiv执行浮点除法,即8.fdiv(3).ceil。Ruby 还提供了一个不错的Rational类:(8/3r).ceil.

