用c语言编写日历

时间:2022-02-23 09:18:18

    查找某一日期所对应的日历表,这一天是所在年份的第几天,这一天是星期几,打印月份日历表:

#include<stdio.h>
#include<windows.h>

int isleap(int year)
{
	if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
		return 1;
	else
		return 0;
}

int max_day(int year, int month)
{
	int day[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	if (isleap(year) == 1)
		day[1] = 29;
	return day[month - 1];
}

int total_day(int year, int month, int day)
{
	int sum = 0;
	int i = 1;
	for (i = 1; i < month; i++)
		sum += max_day(year, i);
	sum += day;
	return sum;
}
int weekday(int year, int month, int day)
{
	int count;
	count = (year - 1) + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400 + total_day(year, month, day);
	count %= 7;
	return count;
}

void display_week(int year, int month, int day)
{
	int count;
	count = weekday(year, month, day);
	switch (count)
	{
	case 0:printf("\t%d-%d-%d is Sunday\n", year, month, day); break;
	case 1:printf("\t%d-%d-%d is Monday\n", year, month, day); break;
	case 2:printf("\t%d-%d-%d is Tuesday\n", year, month, day); break;
	case 3:printf("\t%d-%d-%d is Wednesday\n", year, month, day); break;
	case 4:printf("\t%d-%d-%d is Thursday\n", year, month, day); break;
	case 5:printf("\t%d-%d-%d is Friday\n", year, month, day); break;
	case 6:printf("\t%d-%d-%d is Saturday\n", year, month, day); break;
	default:system("cls");
		printf("error\n");
	}
}

void display_month(int year, int month, int day)
{
	int i = 0, j = 1;
	int week, max;
	week = weekday(year, month, 1);
	max = max_day(year, month);
	printf("\n\t\t\t\t%d年%d月",year,month);
	printf("\n");
	printf("\n\t日\t一\t二\t三\t四\t五\t六\n\n");
	for (i = 0; i < week; i++)
		printf("\t");
	for (j = 1; j <= max; j++)
	{
		printf("\t%d",j);
		if (i % 7 == 6)
			printf("\n\n");
		i++;
	}
	printf("\n\n");
}
int main()
{
	int year, month, day;
	printf("Please enter year,month,day:");
	scanf_s("%d%d%d", &year, &month, &day);
	if (month<1 || month>12 || day<1 || day>31)
	{
		printf("error!");
		return -1;
	}
	printf("%d年%d月%d日是这年的第%d天\n", year, month, day, total_day(year, month, day));
	display_week(year, month, day);
	display_month(year, month, day);
	system("pause");
	return 0;
}

例如:输入2018年3月24日,运行结果如下:

用c语言编写日历