Ruby 检查偶数,浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18163475/
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 check if even number, float
提问by John Smith
I want to check if the number is even! I tried the following:
我想检查数字是否为偶数!我尝试了以下方法:
a = 4.0
a.is_a? Integer
=> false
a.even?
=> undefined method for Float
So how can i check if the number is even?
那么如何检查数字是否为偶数呢?
回答by tigeravatar
If you are unsure if your variable has anything after the decimal and would like to check before converting to integer to check odd/even, you could do something like this:
如果您不确定您的变量是否在小数点后有任何内容,并且想在转换为整数以检查奇数/偶数之前进行检查,您可以执行以下操作:
a = 4.6
b = 4.0
puts a%1==0 && a.to_i.even? #=> false
puts b%1==0 && a.to_i.even? #=> true
Additionally, if you want to create an even? method for the Float class:
此外,如果您想创建一个偶数?Float类的方法:
class Float
def even?
self%1==0 && self.to_i.even?
end
end
a = 4.6
b = 4.0
a.even? #=> false
b.even? #=> true
回答by Yu Hao
Make it an Integerthen:
让它成为Integer:
a = 4.0
a.to_i == a && a.to_i.even? #=> true
回答by zrl3dx
Just keep in mind how numbers are converted:
请记住数字的转换方式:
(4.0).to_i # same as Integer(4.0)
=> 4
(4.5).to_i
=> 4
(4.9).to_i
=> 4
Using roundmay be safer:
使用round可能更安全:
(4.0).round
=> 4
(4.5).round
=> 5
(4.9).round
=> 5
Then of course you can call evenas @Yu Hao wrote:
那么当然你可以even像@Yu Hao 写的那样调用:
(4.5).round.even?
=> false
You can also easily observe known floats 'feature':
您还可以轻松观察已知的浮点数“功能”:
(4.499999999999999).round.even?
=> true
(4.4999999999999999).round.even?
=> false

