c语言实现万年历具体代码
时间: 2023-11-12 14:33:14 浏览: 38
以下是用 C 语言实现万年历的代码:
```c
#include <stdio.h>
int isLeapYear(int year); // 判断是否为闰年
int getDayOfWeek(int year, int month, int day); // 获取指定日期的星期几
void printCalendar(int year, int month); // 打印指定月份的日历
int main()
{
int year, month;
printf("请输入年份和月份(以空格分隔):");
scanf("%d %d", &year, &month);
printCalendar(year, month);
return 0;
}
// 判断是否为闰年
int isLeapYear(int year)
{
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
// 获取指定日期的星期几
int getDayOfWeek(int year, int month, int day)
{
if (month == 1 || month == 2) {
month += 12;
year--;
}
int c = year / 100;
year %= 100;
int week = year + year / 4 + c / 4 - 2 * c + 26 * (month + 1) / 10 + day - 1;
week = (week % 7 + 7) % 7; // 转换为星期几(0-6)
return week;
}
// 打印指定月份的日历
void printCalendar(int year, int month)
{
printf(" %d年%d月\n", year, month);
printf("日 一 二 三 四 五 六\n");
int dayOfWeek = getDayOfWeek(year, month, 1); // 获取当月1号是星期几
int daysInMonth = 31; // 当月总天数
switch (month) {
case 4:
case 6:
case 9:
case 11:
daysInMonth = 30;
break;
case 2:
daysInMonth = isLeapYear(year) ? 29 : 28;
break;
}
int i, j;
for (i = 0; i < dayOfWeek; i++) {
printf(" "); // 输出空格占位
}
for (j = 1; j <= daysInMonth; j++) {
printf("%2d%s", j, (i + j - 6) % 7 == 0 ? "\n" : " "); // 每7天换行
}
if ((i + j - 6) % 7 != 0) {
printf("\n"); // 补齐最后一行的换行
}
}
```
上述代码实现了一个简单的万年历,用户输入年份和月份后,程序会输出该月份的日历。其中,`isLeapYear()` 函数用于判断是否为闰年,`getDayOfWeek()` 函数用于获取指定日期的星期几,`printCalendar()` 函数用于打印指定月份的日历。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![m](https://img-home.csdnimg.cn/images/20210720083646.png)