有功能选择的万年历C语言实现代码
时间: 2024-03-25 10:39:55 浏览: 55
以下是一个带有功能选择的万年历C语言实现代码,可以选择查看指定年份、指定月份、以及指定日期的日历:
```c
#include <stdio.h>
// 计算某年某月的天数
int month_days(int year, int month)
{
int days = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 2:
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
days = 29; // 闰年2月有29天
}
else {
days = 28; // 平年2月有28天
}
break;
default:
days = 30;
break;
}
return days;
}
// 输出日历表头
void print_calendar_header()
{
printf("日\t一\t二\t三\t四\t五\t六\n");
}
// 输出日历表格
void print_calendar(int year, int month, int week_day)
{
int i, j, days;
days = month_days(year, month);
for (i = 0; i < week_day; ++i) {
printf("\t"); // 输出1号前的空格
}
for (i = 1, j = week_day; i <= days; ++i, ++j) {
printf("%d\t", i);
if (j % 7 == 6) {
printf("\n"); // 每输出7个数字换行
}
}
printf("\n");
}
int main()
{
int year, month, day, days, i, week_day, choice;
printf("请选择功能:\n");
printf("1. 查看指定年份的日历\n");
printf("2. 查看指定月份的日历\n");
printf("3. 查看指定日期的日历\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("请输入年份:\n");
scanf("%d", &year);
printf("请输入要查看的月份(1-12):\n");
scanf("%d", &month);
week_day = (year - 1) * 365 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;
for (i = 1; i < month; ++i) {
week_day += month_days(year, i);
}
week_day %= 7;
printf("%d年%d月的日历如下:\n", year, month);
print_calendar_header();
print_calendar(year, month, week_day);
break;
case 2:
printf("请输入年份:\n");
scanf("%d", &year);
printf("请输入要查看的月份(1-12):\n");
scanf("%d", &month);
week_day = (year - 1) * 365 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;
for (i = 1; i < month; ++i) {
week_day += month_days(year, i);
}
week_day %= 7;
printf("%d年%d月的日历如下:\n", year, month);
print_calendar_header();
print_calendar(year, month, week_day);
break;
case 3:
printf("请输入日期(格式:年-月-日):\n");
scanf("%d-%d-%d", &year, &month, &day);
week_day = (year - 1) * 365 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;
for (i = 1; i < month; ++i) {
week_day += month_days(year, i);
}
week_day %= 7;
printf("%d年%d月%d日的日历如下:\n", year, month, day);
print_calendar_header();
print_calendar(year, month, week_day);
break;
default:
printf("无效的输入!\n");
break;
}
return 0;
}
```
该程序通过输入功能选择以及相应的参数,可以选择查看指定年份、指定月份、以及指定日期的日历。具体实现中,使用了多个函数来实现日历表的输出,并且使用了 `switch` 语句来根据用户选择进行不同的操作。
阅读全文