使用 Zeller 算法查找星期
Zeller 算法用来查找给定日期的星期。使用 Zeller 算法查找星期的公式如下
该公式包含一些变量;它们是 -
d - 日期中的天。
m:它是月份代码。从三月到十二月为 3 到 12,对于一月为 13,对于二月为 14。当我们考虑一月或二月时,那么给定的年份将减少 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
广告