实现日历功能,输入年份月份,输出日历
c
#include<stdio.h>
int leap_year(int year)
{
if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
{
return 1;
}else
{
return 0;
}
}
int determine_year_month_day(int *day,int month,int year)
{
if(month != 2)
{
return day[month - 1];
}else
{
return 28 + leap_year(year);
}
}
int date_of_1900(int month,int year,int *day)
{
int i,j;
int sum = 0;
for(i = 1900;i < year;++i)
{
if(leap_year(i) == 1)
{
sum += 366;
}else if(leap_year(i) == 0)
{
sum += 365;
}
}
for(j = 1;j < month;++j)
{
sum += determine_year_month_day(day,j,i);
}
return sum;
}
int printf_calendar(int month,int year,int *day)
{
int i,j,max;
max = determine_year_month_day(day,month,year);
printf(" %d月 %d年 \n",month,year);
printf(" 一 二 三 四 五 六 日\n");
int min = date_of_1900(month,year,day) % 7;
for(j = min;j > 0;--j)
{
printf(" ");
}
for(i = 1;i <= max;++i)
{
printf("%4d",i);
if((i+min) % 7 == 0)
{
putchar('\n');
}
}
}
int main(void)
{
int year,month;
int day[] = {31,28,31,30,31,30,31,31,30,31,30,31};
printf("Please enter the year and month you want to query:");
scanf("%d %d",&year,&month);
if(month > 12 || month < 1)
{
printf("Input Error!\n");
}
printf_calendar(month,year,day);
putchar('\n');
return 0;
}
实现的结果如图所示: