Tips - Visual C#

【TOP】

閏年かどうか判定する
西暦で年を指定して、閏年かどうかを判断してみます。
これにはSystem.DateTime名前空間のIsLeapYearメソッドを用います。
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("終了する場合はCtrl+Cキーを押してください"); while (true) { Console.Write("Year?:"); string inputValue = Console.ReadLine(); int year; if (!int.TryParse(inputValue, out year) || !Regex.IsMatch(inputValue, @"^[1-9][0-9]{0,3}$")) { Console.WriteLine("4桁の整数を入力してください\r\n"); continue; } if (System.DateTime.IsLeapYear(year)) { Console.WriteLine("閏年です\r\n"); } else { Console.WriteLine("閏年ではありません\r\n"); } } } } }
上のプログラムを実行すると以下のような結果となります。
終了する場合はCtrl+Cキーを押してください Year?:2006 閏年ではありません Year?:this year 4桁の整数を入力してください Year?:2004 閏年です Year?:16 閏年です Year?:123456 4桁の整数を入力してください Year?:2008 閏年です Year?:
【戻る】