运用c语言编写一个万年历
时间: 2025-06-16 19:18:53 浏览: 22
### C语言实现万年历的代码示例
以下是基于C语言编写的万年历程序的核心逻辑,该程序可以显示指定日期对应的星期几以及月份的日历布局。
#### 主要功能模块
1. **判断闰年**: 判断某一年是否为闰年的函数。
2. **计算星期**: 使用蔡勒公式或其他方法来计算给定日期是星期几。
3. **打印日历**: 打印某一月或者一整年的日历。
#### 蔡勒公式的应用
蔡勒公式用于快速计算任意一天是星期几。其通用形式如下:
\[
h = \left( q + \lfloor \frac{13(m+1)}{5} \rfloor + K + \lfloor \frac{K}{4} \rfloor + \lfloor \frac{J}{4} \rfloor - 2J \right) \mod 7
\]
其中:
- \( h \): 星期数(0表示周六, 1表示周日...)
- \( q \): 日
- \( m \): 修正后的月份数(3表示三月, ..., 12表示十二月;而1表示十三月即前一年的十一月, 2表示十四月即前一年的十二月)
- \( J \): 年份的前两位数字
- \( K \): 年份的后两位数字
此公式适用于格里高利历之后的时间范围[^1]。
#### 完整代码示例
下面是一个完整的C语言万年历程序示例:
```c
#include <stdio.h>
// 函数声明
int isLeapYear(int year);
void printMonthCalendar(int year, int month);
// 主函数
int main() {
int year;
printf("请输入年份: ");
scanf("%d", &year);
// 遍历并打印全年每个月的日历
for (int i = 1; i <= 12; ++i) {
printMonthCalendar(year, i);
printf("\n"); // 每个月之间留空行
}
return 0;
}
// 判断是否为闰年
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return 1; // 是闰年返回1
} else {
return 0; // 不是闰年返回0
}
}
// 计算某天是一年中的第几天
int getDayOfYear(int year, int month, int day) {
int daysInMonth[] = {31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31};
if (isLeapYear(year)) {
daysInMonth[1] = 29; // 如果是闰年,则二月有29天
}
int totalDays = 0;
for (int i = 0; i < month - 1; ++i) {
totalDays += daysInMonth[i];
}
totalDays += day;
return totalDays;
}
// 获取某天是星期几
int getWeekday(int year, int month, int day) {
static const int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
year -= month < 3;
return (year + year / 4 - year / 100 + year / 400 + t[month - 1] + day) % 7;
}
// 打印一个月的日历
void printMonthCalendar(int year, int month) {
char *months[] = {"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"};
int daysInMonth[] = {31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31};
if (isLeapYear(year) && month == 2) {
daysInMonth[1] = 29;
}
int startDayOfWeek = getWeekday(year, month, 1); // 当月第一天是星期几
printf(" %s %d\n", months[month - 1], year);
printf("Sun Mon Tue Wed Thu Fri Sat\n");
int currentDay = 1;
for (int i = 0; i < startDayOfWeek; ++i) {
printf(" "); // 前面空白填充
}
while (currentDay <= daysInMonth[month - 1]) {
printf("%3d ", currentDay++);
if (((currentDay - 1 + startDayOfWeek) % 7 == 0) ||
(currentDay > daysInMonth[month - 1])) {
printf("\n");
}
}
}
```
以上代码实现了基本的功能需求,包括输入年份后自动打印当年各个月的日历,并考虑了闰年的情况[^1]。
###
阅读全文
相关推荐



















