c语言实现万年历具体代码
时间: 2023-11-12 21:33:54 浏览: 36
好的,下面是实现万年历的 C 语言代码:
```c
#include <stdio.h>
// 判断是否为闰年
int isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
// 获取某年某月的天数
int getDaysOfMonth(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 getWeekday(int year, int month) {
struct tm t = {0};
t.tm_year = year - 1900;
t.tm_mon = month - 1;
t.tm_mday = 1;
mktime(&t);
return t.tm_wday;
}
int main() {
int year, month;
printf("请输入年份:");
scanf("%d", &year);
printf("请输入月份:");
scanf("%d", &month);
// 打印日历表头
printf("日\t一\t二\t三\t四\t五\t六\n");
int days = getDaysOfMonth(year, month);
int weekday = getWeekday(year, month);
// 打印第一行(1号前面的空格)
for (int i = 0; i < weekday; i++) {
printf("\t");
}
for (int i = 1; i <= 7 - weekday; i++) {
printf("%d\t", i);
}
printf("\n");
// 打印中间若干行
int count = 7 - weekday + 1;
while (count <= days) {
for (int i = count; i <= count + 6 && i <= days; i++) {
printf("%d\t", i);
}
printf("\n");
count += 7;
}
return 0;
}
```
这段代码实现了一个简单的万年历功能,可以根据用户输入的年份和月份,输出对应的日历表格。