利用循环输出一个月的日历。要求如下:根据键盘输入内容指定年份类型(闰年、非闰年)、月份和当月1号是星期几,依据上述指定内容输出该月的日历。当输入年份类型(‘y’或‘n’)、月份(1~12)、1号是周几(1~7)不符合要求时能够提示输入错误信息。用数组以前的知识完成
时间: 2024-11-27 21:12:40 浏览: 84
为了利用数组完成这个任务,我们可以创建一个二维数组来存储每个月的日历数据,然后根据输入的年份、月份和一周的第一天来填充这个数组。这里提供一个基本的 C 程序实现思路:
```c
#include <stdio.h>
#include <stdbool.h>
#define MONTHS 12
#define WEEKDAYS 7
bool is_leap_year(int year) {
if (year % 4 != 0) return false;
if (year % 100 != 0) return true;
if (year % 400 != 0) return false;
return true;
}
int days_in_month(int month, int year) {
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
return 31;
case 4: case 6: case 9: case 11:
return 30;
default:
return is_leap_year(year) ? 29 : 28;
}
}
void print_calendar(int start_weekday, int year, int month) {
int calendar[MONTHS][WEEKDAYS] = {0};
int total_days = days_in_month(month, year);
int current_day = 1;
for (int week = 0; week < total_days / WEEKDAYS + ((total_days % WEEKDAYS > start_weekday) ? 1 : 0); week++) {
for (int day = 0; day < WEEKDAYS; day++, current_day++) {
if (current_day <= total_days) {
calendar[month - 1][week * WEEKDAYS + day] = current_day;
} else {
break;
}
}
}
for (int i = 0; i < MONTHS; i++) {
for (int j = 0; j < WEEKDAYS; j++) {
if (calendar[i][j] > 0) {
printf("%2d ", calendar[i][j]);
} else {
printf(" ");
}
}
printf("\n");
}
}
int main() {
char leap_year_input;
int year, month, start_weekday;
printf("请输入年份类型(y/n):");
scanf(" %c", &leap_year_input);
if (leap_year_input != 'y' && leap_year_input != 'n') {
printf("输入错误,请输入 'y' 或 'n'\n");
return 1;
}
if (leap_year_input == 'y') {
year = 2024; // 示例年份,可以根据需要替换
} else {
year = 2023; // 示例年份,可以根据需要替换
}
printf("请输入月份(1~12):");
scanf("%d", &month);
if (month < 1 || month > 12) {
printf("输入错误,请输入1-12之间的整数\n");
return 1;
}
printf("请输入当月1号是周几(1~7):");
scanf("%d", &start_weekday);
if (start_weekday < 1 || start_weekday > 7) {
printf("输入错误,请输入1-7之间的整数\n");
return 1;
}
print_calendar(start_weekday, year, month);
return 0;
}
```
阅读全文
相关推荐


















