c语言万年历简易版
时间: 2025-05-19 10:18:44 浏览: 19
以下是基于所提供的引用内容和专业知识设计的一个简易万年历程序:
### C语言实现简易万年历
以下是一个完整的C语言代码示例,用于实现一个简易的万年历功能。此代码能够接收用户输入的年份和月份,并打印对应月份的日历。
```c
#include <stdio.h>
// 判断是否为闰年
int is_leap_year(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return 1;
}
return 0;
}
// 获取某个月的天数
int get_days_in_month(int year, int month) {
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;
case 2:
return is_leap_year(year) ? 29 : 28;
default:
return -1; // 错误处理
}
}
// 计算给定日期是一年的第几天
int get_day_of_year(int year, int month, int day) {
int days[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 };
int i, sum = 0;
if (is_leap_year(year)) {
days[2] = 29;
}
for (i = 1; i < month; i++) {
sum += days[i];
}
return sum + day;
}
// 计算某一年某一月的第一天是星期几
int get_weekday_of_first_day(int year, int month) {
int day = 1;
int y = year - (month < 3);
int m = month + 12 * ((month <= 2) ? 1 : 0) - 2;
int weekday = (y + y / 4 - y / 100 + y / 400 + (153 * m + 2) / 5 + day) % 7;
return weekday;
}
// 打印日历头部
void print_calendar_header() {
printf(" 日\t一\t二\t三\t四\t五\t六\n");
}
// 打印指定年份和月份的日历
void print_calendar(int year, int month) {
int days = get_days_in_month(year, month);
int start_weekday = get_weekday_of_first_day(year, month);
printf("\n-----------------%d 年 %d 月--------------------\n", year, month);
print_calendar_header();
int i, j;
for (i = 0; i < start_weekday; i++) {
printf("\t");
}
for (j = 1; j <= days; j++, i++) {
printf("%-3d", j);
if (i % 7 == 6) {
printf("\n");
}
}
if (i % 7 != 0) {
printf("\n");
}
}
int main() {
int year, month;
printf("请输入年份:");
scanf("%d", &year);
printf("请输入月份:");
scanf("%d", &month);
if (month >= 1 && month <= 12) {
print_calendar(year, month);
} else {
printf("错误:月份应介于1到12之间。\n");
}
return 0;
}
```
#### 功能说明
上述代码实现了以下几个核心功能:
1. **判断闰年**:通过`is_leap_year()`函数来决定当年是否有2月29日[^1]。
2. **获取每月天数**:利用`get_days_in_month()`函数返回不同月份对应的天数[^1]。
3. **计算每周起始位置**:借助蔡勒公式(Zeller's Congruence),通过`get_weekday_of_first_day()`函数得出当月第一天属于哪一天[^1]。
4. **格式化输出**:最终调用`print_calendar()`完成整个日历表的构建与展示。
#### 注意事项
为了简化逻辑,在实际运行过程中可能还需要考虑更多边界情况以及优化用户体验界面等问题[^2]。
阅读全文
相关推荐















