C#で閏(うるう)年を計算する方法について記述します。
C#の標準メソッドにある DateTime.IsLeapYear(int) を利用すれば、結果をTrueかFalseで返してくれます。
今回は DateTime.IsLeapYear を使用しない場合の実装についても記載したいと思います。
うるう年の計算は下記処理で求めることが可能です。
うるう年の計算方法
① 4で割り切れるか?
→ True:手順2に進む。False:うるう年ではない。
② 100で割り切れるか?
→ True:手順3に進む。False:うるう年です。
③ 400で割り切れるか?
→ True:うるう年です。False:うるう年ではない。
参考までに上記条件分岐のフローチャートも載せておきます。

DateTime.IsLeapYear(不使用版)のソースコード
using System;
class Leap_year
{
public static void Main()
{
int leap_year;
// 判定で使用
Boolean bln = false;
Console.Write("西暦を入力してください:");
string str1 = Console.ReadLine();
leap_year = int.Parse(str1);
// うるう年判断の処理
if(leap_year%4 == 0) {
bln = true;
if(leap_year%100 == 0) {
bln = false;
if(leap_year%400 == 0) {
bln = true;
}
}
} else {
bln = false;
}
if (bln) {
Console.WriteLine(leap_year+"は閏年です。");
} else {
Console.WriteLine(leap_year+"は閏年ではありません。");
}
}
}
出力結果


DateTime.IsLeapYear(使用版)のソースコード
using System;
class Leap_year
{
public static void Main()
{
int leap_year;
// 判定で使用
Boolean bln = false;
Console.Write("西暦を入力してください:");
string str1 = Console.ReadLine();
leap_year = int.Parse(str1);
// うるう年判断の処理
bln = DateTime.IsLeapYear(leap_year);
if (bln) {
Console.WriteLine(leap_year+"は閏年です。");
} else {
Console.WriteLine(leap_year+"は閏年ではありません。");
}
}
}
出力結果


以上です。
この記事が誰かの役に立つことを祈ります。