用c编程实现日历的输出,假如知道了某月1日是星期几、 该月有多少天,就可以借助数组输出该月的日历。比如某个 月份的1号是星期四,该月有30天。请编程实现。
时间: 2023-06-04 16:04:17 浏览: 66
好的,这个问题属于技术问题。以下是使用 C 语言编写的示例代码,可以根据输入的含有日期信息的结构体数组输出对应月份的日历。
```
#include <stdio.h>
#include <stdlib.h>
// 定义日期结构体
struct Date {
int year, month, day;
};
// 定义星期数组和月份数组
char *weekday[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
int monthdays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 判断是否为闰年
int isLeapYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
}
// 求1900年1月1日到当前日期总天数
int totalDays(struct Date d) {
int days = 0, year;
for (year = 1900; year < d.year; year++) {
days += (isLeapYear(year) == 1) ? 366 : 365;
}
for (int month = 0; month < d.month - 1; month++) {
days += monthdays[month];
if (month == 1 && isLeapYear(d.year)) {
days++; // 闰年的二月
}
}
days += d.day - 1;
return days;
}
// 输出日历
void printCalendar(struct Date d) {
int days = totalDays(d);
int week = (days + 1) % 7; // 当月1日星期几
int monthday = monthdays[d.month - 1]; // 当前月份天数
if (d.month == 2 && isLeapYear(d.year)) {
monthday++; // 闰年的二月
}
printf("\n\t %d年%d月\n", d.year, d.month);
printf("Sun Mon Tue Wed Thu Fri Sat\n");
for (int i = 0; i < week; i++) {
printf(" ");
}
for (int i = 1; i <= monthday; i++) {
printf("%3d ", i);
if (++week == 7) {
week = 0;
printf("\n");
}
}
}
int main(void) {
struct Date d;
printf("请输入年月:\n");
scanf("%d%d", &d.year, &d.month);
d.day = 1;
printCalendar(d);
return 0;
}
```
输入示例:
```
请输入年月:
2022 6
```
输出示例:
```
2022年6月
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
```