解题思路:
计算到目标日期天数,再对一周进行取模,得到的便是星期。输出星期前面空格时也很简单,就是上一题个月月末的星期。每个月的天数则可以用这个月的减去上个月的天数得到。
注意事项:
每周有7天,排列大于7天时需要换行。
另外,从每周的第一天从周末开始。
参考代码://1493: 任意年月日日历输出
#include
int countDay(long year, long month)
{
long i, day = 0, days = 0;
if( month
{
year --;
month = 12;
}
for( i = 2007; i
{
if( ( i % 4 == 0 && i % 100 != 0 ) || ( i % 400 == 0) )
day++;
}
days = ( year - 2007 ) * 365 + day;
if( ( year % 4 == 0 && i % 100 != 0 ) || ( i % 400 == 0) )
{
switch(month)
{
case 12: days += 31;
case 11: days += 30;
case 10: days += 31;
case 9: days += 30;
case 8: days += 31;
case 7: days += 31;
case 6: days += 30;
case 5: days += 31;
case 4: days += 30;
case 3: days += 31;
case 2: days += 29;
case 1: days += 31;
}
}
else
{
switch(month)
{
case 12: days += 31;
case 11: days += 30;
case 10: days += 31;
case 9: days += 30;
case 8: days += 31;
case 7: days += 31;
case 6: days += 30;
case 5: days += 31;
case 4: days += 30;
case 3: days += 31;
case 2: days += 28;
case 1: days += 31;
}
}
returndays;
}
int main()
{
long year, month, days, day = 0, i, date = 0;
scanf("%ld %ld", &year, &month);
days = countDay(year, month);
printf("---------------------\n");
printf(" Su Mo Tu We Th Fr Sa\n");
printf("---------------------\n");
//从上一月开始计算月末
if( year == 2007 && month == 1)
{
date = 0;
}
else
date = countDay(year, month - 1) % 7;
date++;
//注意,日历表从周日开始
for( i = 0 ; i
{
printf(" ");
}
for( i = 1; i <= ( countDay(year, month) - countDay(year, month - 1) ); i++)
{
printf("%3ld", i);
date ++;
if(date == 7)
{
printf("\n");
date = 0;
}
}
if(date != 0)
printf("\n");
printf("---------------------");
}