Youbi_correct

JavaScript

ツェラーの公式を使って、年月日からその日の曜日を計算します。

ここでは、現在使われているグレゴリオ暦が始まるより前の年月日についても、当該暦を過去へ延長して適用するものとします(先発グレゴリオ暦)。




計算結果:

コードを展開する

<h2><a id="1" class="mya" href="#1">JavaScript</a></h2>

<p>
<a href="https://ja.wikipedia.org/wiki/?curid=690086">ツェラーの公式</a>を使って、年月日からその日の曜日を計算します。
</p>

<p>
ここでは、現在使われている<a href="https://ja.wikipedia.org/wiki/?curid=823">グレゴリオ暦</a>が始まるより前の年月日についても、当該暦を過去へ延長して適用するものとします(<a href="https://ja.wikipedia.org/wiki/?curid=2457511">先発グレゴリオ暦</a>)。
</p>

<p>
<label>西暦何年?: <input id="year"></label><br>
<label>何月?: <input id="month"></label><br>
<label>何日?: <input id="day"></label>
</p>

<input type="button" value="計算する" id="hoge">

<br>
<p>計算結果: <span id="out"></span></p>

<script>
function floor(a, b) {
  return Math.floor(a/b);
}

function Zeller_c(y, m, d) {
  let Youbi_str = "土日月火水木金";

  if (m < 3) {
    m += 12;
    y -= 1;
  }
  let Y = y%100;

  let ans = floor(26*(m+1), 10)%7 + d%7 + Y%7 + floor(Y, 4)%7 - (2*floor(y, 100))%7 + floor(y, 400)%7;

  return Youbi_str[ans%7];
}

const t = document.getElementById('hoge');
t.addEventListener("click", () => {
  const y = Number(document.getElementById('year').value);
  const m = Number(document.getElementById('month').value);
  const d = Number(document.getElementById('day').value);

  let calender = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  let Answer = "";

  if (y%4 == 0)
    calender[1]++;

  if (m <= 0 || 13 <= m || d <= 0 || calender[m-1] < d)
    Answer += "月日として扱うことができない値が含まれています。"
  else
    Answer += y + "年" + m + "月" + d + "日は " + Zeller_c(y, m, d) + "曜日 です。";

  document.getElementById('out').textContent = Answer;
});
</script>

C++

以下のコードを Wandbox で実行


#include <iostream>
#include <vector>
#include <math.h>

/*
 * ツェラーの公式を使って、年月日から曜日を計算します。
 * 現在使われている、グレゴリオ暦にのみ対応しています(1582年10月15日以降)。
 * 年 月 日 の順に、改行または空白区切りで入力して下さい。
 */

int floor_mine(int a, int b) {
  return std::floor(a / b);
}

std::string Zeller_c(int y, int m, int d) {
  std::vector<std::string> Youbi_vec = {"土", "日", "月", "火", "水", "木", "金"};

  if (m < 3) {
    m += 12;
    y -= 1;
  }
  int Y = y%100;

  int ans = floor_mine(26*(m+1), 10)%7 + d%7 + Y%7 + floor_mine(Y, 4)%7 - (2*floor_mine(y, 100))%7 + floor_mine(y, 400)%7;

  return Youbi_vec[ans%7];
}

int main() {
  int y, m, d;
  std::cin >> y >> m >> d;

  std::string Youbi = Zeller_c(y, m, d);

  printf("%d年%d月%d日は ", y, m, d);
  std::cout << Youbi << "曜日 です。\n";

  return 0;
}

CC0 1.0 Universal