有没有简单的方法确定一个年份是否是闰年?
Date#leap?
函数。now = DateTime.now
flag = Date.leap?( now.year )
例如
Date.leap?( 2018 ) # => false
Date.leap?( 2016 ) # => true
为了您的理解:
def leap_year?(year)
if year % 4 == 0
if year % 100 == 0
if yearVar % 400 == 0
return true
end
return false
end
return true
end
false
end
这可以写成:
def leap_year?(year)
(year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0)
end
试试这个:
is_leap_year = year % 4 == 0 && year % 100 != 0 || year % 400 == 0
class Year
attr_reader :year
def initialize(year)
@year = year
end
def leap?
if @year.modulo(4).zero?
return true unless @year.modulo(100).zero? and not @year.modulo(400).zero?
end
false
end
end
def leap_year?(num)
if num%4 == 0 && num%100 != 0
true
elsif num%400 == 0
true
elsif num%4 == 0 && num%100 == 0 && num%400 != 0
false
elsif num%4 != 0
false
end
end
puts leap_year?(2000)
class Date
def self.leap?(year)
year % 4 == 0 && year % 100 != 0 || year % 400 == 0
end
end
n=gets.to_i
n%4==0 ? n%100==0 ? n%400 ?(puts true):(puts false) :(puts true) :(puts false)
使用尽可能少的比较,您可以这样做:
def leap_year?(year)
# check first if year is divisible by 400
return true if year % 400 == 0
year % 4 == 0 && year % 100 != 0
end
我们可以使用短路 OR (||
) 进行相同的检查:
def leap_year?(year)
year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
end
这是我的方法:
def leap_year?(year)
Time.new(year, 12, 31).yday == 366
end
leap_year?(1999)
#=> false
leap_year?(2000)
#=> true
leap_year?(2100)
#=> false
leap_year?(2104)
#=> true
这个函数接受一个范围参数:
(starting..ending).each do |year|
next if year % 4 != 0
next if year % 100 == 0 && year % 400 != 0
puts year
end
来源:《学习编程》Chris Pine著
flag
?这与闰年有关吗? - Joshua Pinter