使用蔡勒公式查找星期几
可使用蔡勒公式从给定日期查找星期几。使用蔡勒公式查找星期几的公式如下所示
此公式包含一些变量;它们是 -
d - 日期的天份。
m:这是月份代码。从 3 月到 12 月是 3 到 12,对于 1 月是 13,对于 2 月是 14。当我们考虑 1 月或 2 月时,那么给定的年份将减少 1。
y - 年份的最后两位数字
c - 年份的前两位数字
w - 星期几。如果是 0,则是周六,如果是 6,则意味着周五
输入和输出
Input: The day, month and the year: 4, 1, 1997 Output: It was: Saturday
算法
zellersAlgorithm(day, month, year)
输入:日期。
输出:那一周的哪一天(星期日到星期六)。
Begin if month > 2, then mon := month else mon := 12 + month decrease year by 1 y := last two digit of the year c := first two digit of the year w := day + floor((13*(mon+1))/5) + y + floor(y/4) + floor(c/4) + 5*c w := w mod 7 return weekday[w] //weekday will hold days from Saturday to Friday End
示例
#include<iostream> #include<cmath> using namespace std; string weekday[7] = {"Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"}; string zellersAlgorithm(int day, int month, int year) { int mon; if(month > 2) mon = month; //for march to december month code is same as month else { mon = (12+month); //for Jan and Feb, month code will be 13 and 14 year--; //decrease year for month Jan and Feb } int y = year % 100; //last two digit int c = year / 100; //first two digit int w = (day + floor((13*(mon+1))/5) + y + floor(y/4) + floor(c/4) + (5*c)); w = w % 7; return weekday[w]; } int main() { int day, month, year; cout << "Enter Day: "; cin >>day; cout << "Enter Month: "; cin >>month; cout << "Enter Year: "; cin >>year; cout << "It was: " <<zellersAlgorithm(day, month, year); }
输出
Enter Day: 04 Enter Month: 01 Enter Year: 1997 It was: Saturday
广告