Ruby 检查偶数,浮点数 [英] Ruby check if even number, float

查看:42
本文介绍了Ruby 检查偶数,浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查数字是否为偶数!我尝试了以下方法:

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?

推荐答案

如果您不确定您的变量是否在小数点后有任何内容,并且想在转换为整数之前检查以检查奇数/偶数,您可以这样做:

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

另外,如果你想创建一个偶数?Float 类的方法:

Additionally, if you want to create an even? method for the Float class:

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

这篇关于Ruby 检查偶数,浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆