I wrote a program that outputs the year and month. You need to consider the leap year at that time.
--Leap year
--Practice --Problem --Conditions
--Answer
--Supplement
--References
Leap years can be determined under the following conditions.
-① When the Christian era is divisible by 4 ――② However, when it is divisible by 100, it is a normal year. ―― ③ However, if it is divisible by 400, it is a leap year.
Enter the year and month and write a program to find the number of days in that month.
conditions
--Please consider the leap year
def leap_year?(year, month)
#Number of days in each month
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
#Get days from array
days = month_days[month - 1]
#February
if month == 2
#Condition ① When it is divisible by 4
if year % 4 == 0
#Condition ②,③ When the Christian era is divisible by 100 and not divisible by 400
if year % 100 == 0 && year % 400 != 0
days #Not a leap year
else
days + 1 #28th+1 Then it will be 29 days
end
#If it's not divisible by 4, it's not a leap year
else
days
end
#Other than February
else
days
end
end
#Enter the year
p 'Please enter the year'
year = gets.to_i
#Enter month
p 'Please enter the month'
month = gets.to_i
#Method call
days = leap_year?(year, month)
p "#{year}Year#{month}The moon#{days}There are days"
② However, if it is divisible by 100, it is normal. ③ However, if it is divisible by 400, it is a leap year.
In the above answer, such a condition
year % 100 == 0 && year % 400 != 0
It is described like this.
If it is a leap year ** when it is divisible by ** 400, it is a normal year ** if it is not divisible by ** 400. Taking advantage of this, ** else (otherwise) will have a leap year **.
-Free encyclopedia "Wikipedia" (leap year)
-Ruby 3.0.0 Reference Manual (Date # leap?)
Recommended Posts