c语言实现万年历具体代码
时间: 2023-11-12 09:33:20 浏览: 13
以下是使用 C 语言实现万年历的代码:
```c
#include <stdio.h>
// 判断是否是闰年
int isLeapYear(int year)
{
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
// 计算某年某月的天数
int getMonthDays(int year, int month)
{
int days[] = {31, 28 + isLeapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return days[month - 1];
}
// 计算某年某月1号是星期几
int getFirstDayWeek(int year, int month)
{
int day = 1;
for (int i = 1; i < month; i++)
{
day += getMonthDays(year, i);
}
int week = (year - 1 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400 + day) % 7;
return week;
}
// 打印日历
void printCalendar(int year, int month)
{
printf(" %d年%d月\n", year, month);
printf("日 一 二 三 四 五 六\n");
int firstDayWeek = getFirstDayWeek(year, month);
int monthDays = getMonthDays(year, month);
for (int i = 0; i < firstDayWeek; i++)
{
printf(" ");
}
for (int i = 1; i <= monthDays; i++)
{
printf("%2d ", i);
if ((i + firstDayWeek) % 7 == 0)
{
printf("\n");
}
}
if ((monthDays + firstDayWeek) % 7 != 0)
{
printf("\n");
}
}
int main()
{
int year, month;
printf("请输入年份:");
scanf("%d", &year);
printf("请输入月份:");
scanf("%d", &month);
printCalendar(year, month);
return 0;
}
```
运行程序后,输入年份和月份,即可输出对应的日历。注意,该程序没有对输入的年份和月份做范围限制,如果输入不合法的年份或月份,程序可能会出错。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.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)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)