此程序可以输出1~9999年(其实再往后也可以)的任意一年的年历,和终端里的一模一样。
/*
*输出任意1~9999一年年历
*/
#include <stdio.h>
#include <stdlib.h>
#define OK 1;
#define ERROR 0;
/*判断闰年*/
int judgeLeap(int year)
{
if(year < 1800)
{
if(year%4 == 0)
return 1;
else
return 0;
}
else
{
if((year%4 == 0 && year%100 != 0) || (year%400 == 0))
return 1;
else
return 0;
}
}
/*获取1~year这些年中的闰年数*/
int getCountofLeap(int year)
{
int count = 0;
int i = 1;
for(; i < year; i++)
{
if(judgeLeap(i))
count ++;
}
return count;
}
/*获取该年每月第一天位置*/
int getFirstDay(int year, long int * FirstDay)
{
if(year < 1 || year > 9999)//入参判断
{
printf("错误!年份应该在1~9999!\n");
exit(-1);
}
int FirstDay1 = 6;//初始化公元1年第一天位置
int LastDay[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};//平年每月天数
int LeapCount = getCountofLeap(year);//1~year之间的闰年数
//printf("leapcount = %d\n",LeapCount);
long int temp = 365*(year-1);
if(year > 1752)
temp = temp - 11;
FirstDay[1] = (temp+LeapCount+FirstDay1)%7;//该年第一个月第一天的位置
if(judgeLeap(year))//闰年二月特殊考虑
LastDay[2] = 29;
if(year == 1752)
LastDay[9] = 19;
int i = 2;
for(; i < 13; i++)//获取其他月份的第一天位置
{
FirstDay[i] = (LastDay[i-1]+FirstDay[i-1])%7;
}
return OK;
}
/*输出一年*/
int printYear(int year)
{
if(year < 1 || year > 9999)//入参判断
{
printf("错误!年份应该在1~9999!\n");
exit(-1);
}
char Month[12][10] = {"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};
int oneYear[12][6][7] = {};
long int FirstDay[13] = {0};
int LastDay[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
getFirstDay(year, FirstDay);
if(judgeLeap(year))
LastDay[2] = 29;
int month = 0, week = 0, day = 0, first = 1, last = 1;
for(month = 0; month < 12; month++)
{
first = 1; last = 1;
for(week = 0; week < 6; week++)
{
for(day = 0; day < 7; day++)//输出一周
{
if( first > FirstDay[month+1] && last <= LastDay[month+1])
{
oneYear[month][week][day] = last;
if(year == 1752 && month == 8 && last == 2)//1752年9月特殊考虑
last = last + 11;
last ++;
}
else
oneYear[month][week][day] = 0;
first ++;
}
}
}
//printf("%d\n",oneYear[1][0][6]);
int i = 0, j = 0;
for(i = 0; i < 4; i++)
{
printf("\t %s\t\t\t %s\t\t\t %s\n",Month[j],Month[j+1],Month[j+2]);
printf(" 日 一 二 三 四 五 六\t 日 一 二 三 四 五 六\t 日 一 二 三 四 五 六\n");
for(week = 0; week < 6; week++)
{
for(month = j; month < j+3; month++)
{
for(day = 0; day < 7; day++)//输出一周
{
if(oneYear[month][week][day] == 0)
printf("%3c",' ');
else
printf("%3d",oneYear[month][week][day]);
}
printf("\t");
}
printf("\n");
}
j = j+3;
}
return 0;
}
int main(int argc, char * argv[])
{
int year = 1;
printf("请输入一个年份:");
scanf("%d",&year);
printf("\n\t\t\t\t%d年\n\n",year);
printYear(year);
return 0;
}
执行效果: