c++练习3-5:打印日历
时间: 2024-05-15 14:18:20 浏览: 78
好的,我可以为您提供练习3-5的代码,让您能够打印出指定年月的日历。以下是示例代码:
```
#include <stdio.h>
int is_leap_year(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return 1;
}
return 0;
}
int get_days_in_month(int year, int month) {
int days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2) {
if (is_leap_year(year)) {
return 29;
} else {
return 28;
}
}
return days_in_month[month - 1];
}
void print_calendar(int year, int month) {
int days_in_month = get_days_in_month(year, month);
int first_day_of_week = 1;
printf("日\t一\t二\t三\t四\t五\t六\n");
for (int i = 1; i <= days_in_month; i++) {
if (i == 1) {
for (int j = 0; j < first_day_of_week; j++) {
printf("\t");
}
}
printf("%d\t", i);
if ((i + first_day_of_week) % 7 == 0 || i == days_in_month) {
printf("\n");
}
}
}
int main() {
int year, month;
printf("请输入年份和月份(格式:年份 月份):");
scanf("%d %d", &year, &month);
printf("%d年%d月的日历如下:\n", year, month);
print_calendar(year, month);
return 0;
}
```
您可以将代码复制粘贴到您的 C 语言开发环境中运行,输入需要打印的年份和月份即可得到对应的日历。希望对您有帮助!
阅读全文