你好!
星期几的算法有以下两种:
W=[Y-1]+[(Y-1)/4]-[(Y-1)/100]+[(Y-1)/400]+D
Y是年份,D是这一天在这一年中的累积天数,也就是这一天在这一年中是第几天。
W=[C/4]-2C+y+[y/4]+[13*(m+1)/5]+d-1
C是世纪数减1
y是年份后两位
M是月份,d是日数
1月和2月要按上一年的13月和14月来算,这时C和y均按上一年取值
两个公式中的[]均指只取整数部分
算出来的W余几就是星期几,0=日
参考例子:(测试正确)
#include
bool IsLeapYear(int nYear)
{
return ((!(nYear % 4) && nYear % 100) || !(nYear % 400));
}
int CalcWeekday(int nYear, int nMonth, int nDay)
{
/*
W=[Y-1]+[(Y-1)/4]-[(Y-1)/100]+[(Y-1)/400]+D
Y是年份,D是这一天在这一年中的累积天数,也就是这一天在这一年中是第几天。
*/
int DT[] = {1, 4, 4, 0, 2, 5, 0, 3, 6, 1, 4, 2};
int nDayIn = (nMonth > 2) ? ((IsLeapYear(nYear) ? (DT[nMonth - 1] + 1) : DT[nMonth - 1])) : DT[nMonth - 1];
int nWeekday = (nYear - 1 + (nYear - 1)/4 - (nYear - 1)/100 + (nYear - 1)/400 + nDayIn) % 7;
// 算出本月第一天为星期几
nWeekday = (nWeekday < 0) ? (nWeekday + 7) : nWeekday;
// 返回该天为星期几
return (nWeekday + nDay - 1) % 7;
}
int main()
{
int nYear, nMonth, nDay;
char arrDayName[][25] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
printf("Year Month Day: ");
scanf("%d %d %d", &nYear, &nMonth, &nDay);
printf("%d-%d-%d:%s\n", nYear, nMonth, nDay, arrDayName[CalcWeekday(nYear, nMonth, nDay)]);
return 0;
}
希望我的回答能对你有所帮助!
如果还有问题,可以BaiduHi我,O(∩_∩)O~!
#include
#include
int D(int year)
{
long int i,sum=0,T;
for(i=1950;i
if(i%400==0||i%4==0&&i%100!=0) T=366;
else T=365;
sum=sum+T;
}
return sum;
}
int M(int year,int month)
{
long int days,i,d;
days=0;
for(i=1;i
switch(i)
{
case 1:case 3: case 5:case 7:case 8:case 10:case 12:d=31;break;
case 4:case 6:case 9:case 11: d=30;break;
case 2:if(year%400==0||year%4==0&&year%100!=0)d=29;
else d=28;
}
days=days+d;
}
return days;
}
main()
{
int i,j,k,d,year,month,day;
printf("please input year.month.day:\n");
scanf("%d%d%d",&year,&month,&day);
k=(D(year)+M(year,month))%7;
switch(month)
{
case 1:case 3:case 5:case 7:case 8:case 10:case 12:d=31;break;
case 4:case 6:case 9:case 11: d=30;break;
case 2:if(year%400==0||year%4==0&&year%100!=0)d=29;
else d=28;
}
printf("\n\n\n\n");
printf(" %d-%d-%d\n\n",year,month,day);
printf(" Sunday Monday Tuesday Wednesday Thursday Friday Saturday\n");
for(i=1;i<=k;i++)printf(" ");
for(i=1;i<=7-k;i++)printf("%10d",i);printf("\n\n");
for(j=8-k;j<=d;j++)
{
printf("%10d",j);
if((j+k)%7==0)printf("\n\n");
}
getch();
}