先出個小題目考考大家,給你任意一個日期,計算出當天對應得是周幾。
想想看怎么實現?不要撓頭,慢慢來哈。
先看一下上面提到得神奇代碼實現得效果
驗證一下
什么還要歷史上得今天,來來來,繼續
驗證下
具體怎么實現得呢
不多廢話直接上代碼
#include <stdio.h>
#include <stdlib.h>
unsigned char week_check(int year,int month ,int day);
unsigned char* Tweek[7] = {"星期天","星期一","星期二","星期三","星期四","星期五","星期六"};
int main(int argc, char *argv[]) {
int year=0;
int mon=0;
int day=0;
unsigned char weekday=0;
while(1)
{
printf("請輸入日期,如2021年3月1日請輸入2021-3-1 \n\r");
scanf("%d-%d-%d",&year,&mon,&day);
weekday = week_check(year,mon,day);
printf("%d年%d月%d日是%s! \n\r\n\r", year,mon,day, Tweek[weekday]);
}
return 0;
}
unsigned char week_check(int year,int month ,int day)
{
int week=0x00;
if (month == 1 || month == 2)
{
year = year - 1;
month = month + 12;
}
week = (day + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400 + 1) % 7;
return week;
}
怎么樣是不是沒有想象得那么復雜,只有簡簡單單得幾行代碼,很神奇吧。
不知道是哪位大神腦洞出奇想到了這個算法,你看懂了么?可以交流下哈