c编程日历怎么写

时间:2025-03-01 00:41:07 明星趣事

在C语言中编写一个简单的日历程序可以通过以下步骤实现:

获取用户输入的年份和月份

使用`printf`提示用户输入年份和月份。

使用`scanf`读取用户输入的年份和月份。

定义月份和星期的数组

创建一个包含12个月的字符串数组,用于存储每个月的名字。

创建一个包含7个元素的字符串数组,用于存储星期的名字(星期日到星期六)。

计算每个月的天数

根据年份判断闰年,并据此计算每个月的天数。

闰年2月有29天,平年2月有28天。

计算输入月份的第一天是星期几

使用Zeller公式或其他方法计算输入月份的第一天是星期几。

打印日历

使用嵌套循环遍历月份和日期,打印出每个月的日历。

打印出每个月的标题行,包括月份和星期的名字。

打印出每个月的日期,并根据计算出的第一天是星期几进行对齐。

```c

include

include

define MAX_MONTHS 12

define MAX_DAYS_PER_MONTH 31

define MAX_WEEKDAYS 7

char *months[MAX_MONTHS] = {

"January", "February", "March", "April", "May", "June",

"July", "August", "September", "October", "November", "December"

};

char *weekdays[MAX_WEEKDAYS] = {

"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"

};

int isLeapYear(int year) {

return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

}

int getDaysInMonth(int year, int month) {

int days[MAX_MONTHS] = {31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

return days[month - 1];

}

int getFirstDayOfWeek(int year, int month) {

int y = year - 1900;

int m = month - 1;

int d = 1;

int w = (y / 4 - y / 100 + y / 400 + (13 * (m + 1) / 5) + d - 1) % 7;

return (w + 6) % 7;

}

void printCalendar(int year, int month) {

int firstDayOfWeek = getFirstDayOfWeek(year, month);

int daysInMonth = getDaysInMonth(year, month);

int totalDays = 0;

printf(" %s %d\n", months[month - 1], year);

printf("Sun Mon Tue Wed Thu Fri Sat\n");

for (int i = 0; i < firstDayOfWeek; i++) {

printf("");

}

for (int day = 1; day <= daysInMonth; day++) {

if (totalDays % 7 == firstDayOfWeek) {

printf("\n");

}

printf("%4d", day);

totalDays++;

if (totalDays % 7 == 0) {

printf("

");

}

}

printf("

");

}

int main() {

int year, month;

printf("请输入年份: ");

scanf("%d", &year);

printf("请输入月份: ");

scanf("%d", &month);

if (month < 1 || month > 12) {

printf("无效的月份输入。

");

return 1;

}

printCalendar(year, month);

return 0;

}

```

这个程序首先定义了月份和星期的数组,然后通过`isLeapYear`函数判断闰年,通过`getDaysInMonth`函数获取每个月