本程序运用的万年历的计算公式: d=a-1+(a-1)/4-(a-1)/100+(a-1)/400+c;
其中a为年c为该日期在本年中的天数,d取整数,当d/7余数0时是星期天,余数1时是星期一依此类推。
#include <stdio.h>
int m_day(int year,int month)/*此函数是给定年,月,计算此月有多少天.*/
{
if ((year%4==0 &&year%100!=0) ¦¦ (year%400==0))
switch(month)
{
case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
case 4: case 6: case 9: case 11: return 30;
case 2: return 29;
}
else
switch(month)
{
case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
case 4: case 6: case 9: case 11: return 30;
case 2: return 28;
}
}
int main()
{
int year,month;
int i,days=0,d,day=0;
printf("Enter the year and month:\n");
scanf("%d%d",&year,&month);
for (i=1;i<month;i++)
days+=m_day(year,i);
d=year-1+(year-1)/4-(year-1)/100+(year-1)/400+days+1;
printf("%d-%d\n",year,month);
printf(" Sun Mon Tue Wed Thu Fri Sat\n");
for (i=0;i<d%7;i++)
printf(" ");
for (i=1;i<=7-d%7;i++)
{
day++;
printf("%5d",day);
}
printf("\n");
while(1)
{
for (i=1;i<=7;i++)
{
day++;
if (day>m_day(year,month)) {getch();return 0;}
printf("%5d",day);
}
printf("\n");
}
}