LoginSignup
0
1

More than 1 year has passed since last update.

【Ruby 】【閏年問題】西暦の年数および月を入力し、その月の日数を求めよ

Last updated at Posted at 2021-05-08
def get_days(year, month)
  month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
              #[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]列目
    if month == 2   
        if year % 4 == 0  
            if year % 100 == 0 && year % 400 != 0 
              days = 28
            else
              days = 29
            end
        else
          days = 28
        end
    else
      days = month_days[month - 1]
    end
  return days
end


puts "年を入力してください:"
year = gets.to_i
puts "月を入力してください:"
month = gets.to_i

days = get_days(year, month)
puts "#{year}#{month}月は#{days}日間あります"

閏年は以下の判断基準で決まる。

①その西暦が4で割り切れたら閏年である
②ただし、例外として100で割り切れる西暦の場合は閏年ではない
③ただし、その例外として400で割り切れる場合は閏年である

つまり、西暦2000年は閏年であり、西暦2100年は閏年ではありません。
これらに対応できるように、出力例と雛形をもとに実装しましょう。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1