c语言编写程序, 读入任一年份,模拟挂历输出该年年历, 要求每两月并排显示。每个日期占4位,左右月份间空8位,标题位于相应中间位置,年历标题和每月后空一行。
时间: 2023-05-28 12:06:22 浏览: 314
以下是一个示例程序:
```
#include <stdio.h>
int is_leap_year(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
int days_in_month(int year, int month) {
int days[12] = {31, 28 + is_leap_year(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return days[month - 1];
}
void print_month(int year, int month) {
char *months[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
printf("%s\n", months[month - 1]);
printf("Sun Mon Tue Wed Thu Fri Sat\n");
int days = days_in_month(year, month);
int weekday = 0;
for (int i = 1; i <= days; i++) {
if (weekday == 0) {
printf("%*d", 3, i);
} else {
printf(" %*d", 3, i);
}
if (++weekday == 7) {
printf("\n");
weekday = 0;
}
}
if (weekday != 0) {
printf("\n");
}
printf("\n");
}
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
printf("\n");
printf("%*s\n\n", 22, "Year Calendar");
for (int month = 1; month <= 12; month += 2) {
print_month(year, month);
if (month != 11) {
printf("%*s\n\n", 8, "");
}
}
return 0;
}
```
该程序定义了两个辅助函数 `is_leap_year` 和 `days_in_month`,用于判断闰年和计算每个月的天数。主函数中先读入年份,然后循环输出每两个月的月历,期间输出空格以分隔左右两边的月份。每个月的月历通过 `print_month` 函数实现,该函数输出月份名称、星期几的标题,以及每一天的日期。日期的输出使用了 `%*d` 格式化字符串,其中 `*` 表示输出宽度,可以根据需要调整。
阅读全文