编写一个日历程序,以1990年为基准(1990年第一天为星期一),要求输入一个年月,输出对应月份的日历表
执行结果:
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int month_day_num[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};//存放每一个月的天数
int IsLeapYear (int year) //判断是不是闰年
{
return ((year%4==0&&year%100!=0) || (year%400==0));//是闰年返回1,不是闰年返回零
}
//求一年的第一天是星期几,以1990年为基准(1990年第一天是星期一)
int first_day_of_year(int year)
{
int i = 0;
int day_num = 0;
assert (year > 1990);
for (i=1990; i<year; i++)
{
day_num += (365+IsLeapYear (i));
}
return (day_num%7)+1;
}
//求某一年的某一月第一天是星期几
int first_day_of_month(int year, int month, int first_day)
{
int i = 0;
int day_num = 0;
assert (month>0 && month<13);
for (i=1; i<month; i++)
{
day_num += month_day_num[IsLeapYear (year)][i];
}
return (day_num+first_day)%7;
}
void print(int year, int month)
{
int i = 0;
int first_day = first_day_of_month(year, month, first_day_of_year(year));
if (first_day == 0)
{
first_day = 7;
}
printf ("%d年%d月:\n", year, month);
printf ("一\t二\t三\t四\t五\t六\t天\n\n");
for (i=0; i<first_day-1; i++)
{
printf ("\t");
}
for (i=0; i<month_day_num[IsLeapYear(year)][month]; i++)
{
printf ("%d\t", i+1);
if ((i+first_day)%7 == 0)
{
printf ("\n\n");
}
}
printf ("\n");
}
int main()
{
int year = 0;
int month = 0;
int f;
while (1)
{
printf ("请按以下格式输入年月:year/month:");
scanf ("%d/%d", &year, &month);
printf("\n");
print(year, month);
/*scanf ("%d", &year);*/
/*f = first_day_of_year(year);
printf("%d\n", f);*/
}
system ("pause");
return 0;
}