3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

うるう年判定の練習

Posted at

問題

入力された整数がグレゴリオ暦(いつも使ってるやつ)でうるう年であるか判定せよ

こちらのサイトから引用

解答

leap_year.rb
# 結果を表示するメソッド
def year_show(current_year, leap_judge)
  # うるう年だった場合
  if leap_judge
    puts "#{current_year}年はうるう年です"
    
  # うるう年ではなかった場合
  else
    puts "#{current_year}年はうるう年ではありません"
  end
end

# 西暦を入力
print "西暦を入力してください : "
YEAR_JUDGE = gets.to_i

# case文でうるう年判定
case
# 400で割り切れたらうるう年
when YEAR_JUDGE % 400 == 0
  year_show(YEAR_JUDGE, true)
  
# 100で割り切れたらうるう年ではない
when YEAR_JUDGE % 100 == 0
  year_show(YEAR_JUDGE, false)
  
# 4で割り切れたらうるう年
when YEAR_JUDGE % 4 == 0
  year_show(YEAR_JUDGE, true)

# それ以外はうるう年ではない  
else
  year_show(YEAR_JUDGE, false)
end

結果

西暦を入力してください : 2015
2015年はうるう年ではありません

西暦を入力してください : 2016
2016年はうるう年です

3
3
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?