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