使用蔡勒公式查詢星期幾
可使用蔡勒公式從給定日期查詢星期幾。使用蔡勒公式查詢星期幾的公式如下所示
此公式包含一些變數;它們是 -
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
廣告