C++ 中的星期幾
假設我們有一個日期(日、月和年)。根據此日期,我們必須找到該給定日期的星期幾。為了解決這個問題,我們將使用蔡勒公式。以下是使用蔡勒公式查詢星期幾的公式
𝑤=$$\lgroup d+\lfloor \frac{13(m+1)}{5} \rfloor+y+\lfloor\frac{y}{4} \rfloor+\lfloor\frac{c}{4} \rfloor+5c \rgroup mod 7$$
公式包含一些變數;它們是 −
d − 日期中的日。
m − 它是月份程式碼。對於 3 月到 12 月,它是 3 到 12,對於 1 月是 13,對於 2 月是 14。當我們考慮 1 月或 2 月時,則給定的年份將減少 1。
y − 年份的後兩位數字
c − 年份的前兩位數字
w − 星期幾。當它為 0 時,表示星期六,當它為 6 時,表示星期五
例如,如果我們想獲取 1997 年 1 月 4 日的星期幾,則輸出將為“星期六”
演算法如下 −
演算法
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
示例 (C++)
#include
#include
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);
}輸入
(4, 1, 1997)
輸出
Enter Day: 4 Enter Month: 1 Enter Year: 1997 It was: Saturday
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP