偶然的机会看到了一个计算星期几的算法,感觉很怪异并且很有意思就记录一下,也与大家共勉。自己写的代码有些瑕疵,但重点是计算星期的算法值得思索。有不正确的地方希望多多指正。
问题:输入年月日计算是星期几?
代码如下:
include <stdio.h>
int getWeek(int year, int month, int day)
{
int aWeek[12] = {0,3,2,5,0,3,5,1,4,6,2,4};
int week = 0;
int temp = 0;
if(year < 1 || month < 1 || month > 12 || day < 1 || day > 31)
{
return 0;
}
year -= month < 3;
temp = (year + year/4 - year/100 + year/400 + aWeek[month-1] + day) % 7;
switch(temp)
{
case 0: week = 7;break;
case 1: week = 1;break;
case 2: week = 2;break;
case 3: week = 3;break;
case 4: week = 4;break;
case 5: week = 5;break;
case 6: week = 6;break;
default: week = 0;break;
}
return week;
}
int main()
{
int year = 0;
int month = 0;
int day = 0;
int week = 0;
while(1)
{
printf("Please input date:(year month day)\n");
scanf("%d %d %d", &year, &month, &day);
week = getWeek(year, month, day);
if(week < 1 || week > 7)
return 0;
printf("date:%d-%d-%d is %d of week\n", year, month, day, week);
}
return 0;
}
网友评论