C语言--实现万年历

一、思路:
  1. 判断某年是否为闰年
  2. 判断某年的某一天是星期几(有固定的公式)
  3. 按一定的格式输出
二、代码:
#include

int judge_year(int year)  //判断是否是闰年
{
	if ((year / 4 == 0) && (year / 100 != 0) || (year / 100 == 0))
		return 366;
	else 
		return 365;
}

int printf(int year)   //打印日历
{
	int month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};  //存放月份
	static int mon = 1;
	int week, day = 0;

	if ( judge_year(year) == 366)
	{
		month[1] = 29;
	}

	for (int i = 0; i < 12; i++)
	{
		printf("\n");
		printf("%9d 月 \n", mon++);
		printf("%s \n", "一 二 三 四 五 六 日");

		bool flag = true;
		for(int j = 1; j <= month[i]; j++)
        {
			++day;
			week = ((year-1) + (year-1)/4 - (year-1)/100 + (year-1)/400 + day) % 7;   //判断某年某一天是星期几

			if (week == 1) 
			{
				flag = false;
			}
			if ((week > 1 && flag) || week == 0)
			{
				if (week == 0 && j == 1) //判断每个月的1号是否为星期天
				{
					printf("                  ");
				}
				for (int k = 1; k < week; k++)
				{
					printf("   ");
				}

				flag = false;
			}
			printf("%-3d", j);
    
			if (week % 7 == 0)  //如果为星期天,则换行
			{
				printf("\n");
			}
			if (day == 365 || day == 366)
			{
				printf("\n");
			}
        }

	}

	return 0;

}

int main()
{
	int year;
	
	printf("请输入年份:\n");
	scanf("%d", &year);
	
	judge_year(year);
	printf(year);

	return 0;
}
注:编译环境为VS2010.

你可能感兴趣的:(C程序)