生まれた日から今日まで、何日生きているのかを求める2
概要
前回作ったコードが意外と面白かったので C# に移植してアプリにした。ダウンロードはこちらから → Download ( 5KB )
プロジェクト一式のダウンロードはこちらから → Download ( 187KB )
当初公開したバージョンにはバグがありました。すみません。本バージョンでは修正済みです。そのため下記のアプリ画面で出力されている 254 という値は間違いです。
![]() |
| アプリ画面 |
コード
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CalcLivedDays
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// うるう年判定, 第一引数 判定する年、うるう年ならば 1 を返す
private int IsUruu(int y)
{
if (y % 400 == 0) {
return (1);
}
else if (y % 100 == 0) {
return (0);
}
else if (y % 4 == 0) {
return (1);
}
return (0);
}
private void button1_Click(object sender, EventArgs e)
{
// 計算します。
int b_y = 0, b_m = 0, b_d = 0;
try {
b_y = int.Parse(textBox1.Text);
b_m = int.Parse(textBox2.Text);
b_d = int.Parse(textBox3.Text);
if (b_y < 0 || b_m <= 0 || b_d < 0) {
throw new Exception("あそばないのっ!");
}
}
catch (Exception exc) {
MessageBox.Show("そうやって不正なデータを入力して遊ぶの良くない。\r\n" + exc.ToString(), "ERROR");
return;
}
// 今日の日付を取得
DateTime dt = DateTime.Now;
int n_y = dt.Year, n_m = dt.Month, n_d = dt.Day;
int countDay = 0;
int[] last_day = new int[] { 31,28,31,30,31,30,31,31,30,31,30,31 };
// for の条件判定は 0 から開始で 1 から開始ではないので引く
b_m -= 1;
n_m -= 1;
// 手順
// 1.まず今日までの日数をすべて足す。この際うるう年であるならば、366 を足す
// 1.2 そして、誕生した年の生まれる前までの日数をすべて引く
// 1.3 その後、現在のまだ経過していない日数を引く。
for (int i = b_y; i <= n_y; i++) {
countDay += 365 + IsUruu(i);
}
// 1.2
for (int i = 0; i < b_m; i++) {
// うるう年の 2 月 29日を処理する。
if (IsUruu(b_y) == 1 && i == 1) {
countDay -= 29;
}
else {
countDay -= last_day[i];
}
}
countDay -= b_d;
// 1.3
for (int i = 12 - 1; i >= n_m; i--) {
if (IsUruu(n_y) == 1 && i == 1) {
countDay -= 29;
}
else {
countDay -= last_day[i];
}
}
countDay += n_d;
MessageBox.Show("あなたは今日まで " + countDay + " 日生きています。", "Answer");
}
}
}
