如何用c语言制作万年历,要求包括闰年判断,星期判断,年历输出,月历输出
时间: 2024-12-23 11:24:15 浏览: 11
用C语言制作万年历,首先需要考虑闰年的判断、星期的计算以及详细的日期输出。这里提供一个基础的示例,使用`stdio.h`和`time.h`库:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 判断是否是闰年
int is_leap_year(int year) {
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) return 1;
return 0;
}
// 获取给定日期对应的星期几
char get_weekday(int day, int month, int year) {
time_t raw_time;
struct tm * timeinfo;
time(&raw_time);
timeinfo = localtime(&raw_time);
// 调整月份和日子,因为localtime默认从1月1日开始
timeinfo->tm_mon = month - 1; // 0-based index
timeinfo->tm_mday = day;
// 重构日期并获取星期
mktime(timeinfo);
return (char)(timeinfo->tm_wday + 1); // Monday is 1, Sunday is 7
}
void print_calendar(int year, int month) {
printf("%s\n", calendar_names[month - 1]);
printf("-------------------------\n");
int days_in_month = is_leap_year(year) ? 29 : (month == 2 && !is_leap_year(year) ? 28 : (month > 2 ? 30 : 31));
for (int i = 1; i <= days_in_month; ++i) {
printf("%2d ", i);
// 输出星期几
char weekday = get_weekday(i, month, year);
switch (weekday) {
case '1':
printf("| ");
break;
case '2':
printf("|/");
break;
case '3':
printf("|\\");
break;
case '4':
printf("| ");
break;
case '5':
printf("|-");
break;
case '6':
printf("|_");
break;
case '7':
printf("|+");
break;
}
if ((i % 7) == 0) {
printf("\n");
}
}
printf("\n");
}
// 常量定义
const char* calendar_names[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
int main() {
int year = 2023, month = 1;
while (true) {
printf("Year: %d\nMonth: %s\n", year, calendar_names[month - 1]);
print_calendar(year, month);
printf("\nDo you want to continue? (y/n): ");
char input[2];
fgets(input, sizeof(input), stdin);
input[0] = toupper(input[0]); // 将输入转换为大写
if (input[0] != 'Y') break;
scanf("%d", &month); // 验证用户输入是否合法
if (month < 1 || month > 12) month = 1; // 设置回月
year++;
}
return 0;
}
阅读全文