0
0

More than 1 year has passed since last update.

西暦の年数および月を入力し、その月の日数を求めるプログラムの備忘録

Posted at

今日も学んだことを忘れない為にメモします。

プログラム内容

西暦の年数および月を入力し、その月の日数を求めるプログラムを書く。
その場合、閏年について考慮する必要がある。

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

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

1990年2月 =>"1990年2月は28日間あります"
2000年2月 =>"2000年2月は29日間あります"
2100年2月 =>"2100年2月は28日間あります"
2000年3月=>"2000年3月は31日間あります"

記述内容

def get_days(year, month)
  month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  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}日間あります"

各月の日数は配列で管理する
2月以外は各月の日数が決まってるのでまずは以下のようにコードを記述する。

def get_days(year, month)
  month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 各月の日数は配列で管理
  return month_days[month - 1]
end

次に2月の場合のコードを記述(if month == 2で 2月の時の記述)

def get_days(year, month)
  month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  if month == 2
  else
    days = month_days[month - 1]
  end

閏年のときは2月は29日、、それ以外の年は28日になる。
閏年の条件は3つあるが、以下のようにまとめることができる。
① その年が4で割り切れること
② ただし、年が100で割り切れて400で割り切れない場合は閏年ではない

したがって、以下のような条件分岐を設けることができる。

year = 指定の年

if year % 4 == 0  
  if year % 100 == 0 && year % 400 != 0 
    # 閏年でない
  else
    # 閏年
  end
end

if year % 4 == 0 は年が4で割り切れる場合
if year % 100 == 0 && year % 400 != 0 は年が100で割り切れて400で割り切れない場合

上記のロジックを反映する。

def get_days(year, month)
  month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  if month == 2
    if year % 4 == 0  # 年が4で割り切れること
      if year % 100 == 0 && year % 400 != 0  # 年が100で割り切れて400で割り切れない場合
        days = 28 # 閏年でない
      else
        days = 29 # 閏年
      end
    else
      days = 28   # 閏年でない
    end
  else
    days = month_days[month - 1]
  end

  return days
end

以上になります。

0
0
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
0