C语言打印任意年份日历3*4
时间: 2023-06-14 11:05:15 浏览: 146
C语言日历,可打印任意年份的月份
4星 · 用户满意度95%
以下是C语言代码,可以打印任意年份的日历,每页显示3行4列:
```c
#include <stdio.h>
#include <stdlib.h>
int isLeapYear(int year) {
if (year % 400 == 0) {
return 1;
} else if (year % 100 == 0) {
return 0;
} else if (year % 4 == 0) {
return 1;
} else {
return 0;
}
}
int getDaysOfMonth(int year, int month) {
int days = 0;
if (month == 2) {
if (isLeapYear(year)) {
days = 29;
} else {
days = 28;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
days = 30;
} else {
days = 31;
}
return days;
}
int getDayOfWeek(int year, int month, int day) {
int days = 0;
for (int i = 1900; i < year; i++) {
if (isLeapYear(i)) {
days += 366;
} else {
days += 365;
}
}
for (int i = 1; i < month; i++) {
days += getDaysOfMonth(year, i);
}
days += day - 1;
return (days + 1) % 7;
}
void printCalendar(int year, int month) {
int days = getDaysOfMonth(year, month);
int firstDayOfWeek = getDayOfWeek(year, month, 1);
printf("%d年%d月\n", year, month);
printf("日 一 二 三 四 五 六\n");
for (int i = 0; i < firstDayOfWeek; i++) {
printf(" ");
}
for (int i = 1; i <= days; i++) {
printf("%2d ", i);
if ((firstDayOfWeek + i) % 7 == 0) {
printf("\n");
}
}
printf("\n");
}
int main() {
int year, month;
printf("输入年份:");
scanf("%d", &year);
printf("输入月份:");
scanf("%d", &month);
for (int i = 0; i < 12; i += 3) {
printf("\n");
for (int j = 0; j < 4; j++) {
printCalendar(year, i + j + 1);
}
}
return 0;
}
```
这段代码会先让用户输入年份和月份,然后使用 `printCalendar` 函数打印对应月份的日历。最后,使用两个嵌套循环,每页打印3行4列,调用 `printCalendar` 函数即可。
阅读全文