运用C语言编程实现一款简单万年历。要求输出的界面尽可能整齐、美观,符合万年历显示规范。具体功能如下: 输入年月日,计算相应日期是星期几。 输入年月,输出相应月份的日历。输入年份,输出该年所有日历。 具有退出功能。
时间: 2024-03-24 16:39:11 浏览: 81
以下是使用C语言实现的简单万年历程序:
```c
#include <stdio.h>
// 计算某一天是星期几
int dayOfWeek(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;
return week;
}
// 判断是否为闰年
int isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
// 输出某年某月的日历
void printMonth(int year, int month) {
int days_of_month[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
if (isLeap(year)) {
days_of_month[2] = 29;
}
int week = dayOfWeek(year, month, 1);
printf(" %d年%d月\n", year, month);
printf("Sun Mon Tue Wed Thu Fri Sat\n");
for (int i = 0; i < week; i++) {
printf(" ");
}
for (int i = 1; i <= days_of_month[month]; i++) {
printf("%3d ", i);
if ((i + week) % 7 == 0) {
printf("\n");
}
}
printf("\n");
}
// 输出某年的日历
void printYear(int year) {
for (int i = 1; i <= 12; i += 3) {
printf("\n");
for (int j = 0; j < 4; j++) {
printMonth(year, i + j);
}
}
}
int main() {
int year, month, day, week;
while (1) {
printf("请选择功能:\n");
printf("1. 输入年月日,计算星期几\n");
printf("2. 输入年月,输出月份日历\n");
printf("3. 输入年份,输出该年所有日历\n");
printf("4. 退出\n");
int choice;
scanf("%d", &choice);
if (choice == 1) {
printf("请输入年月日,用空格分隔:");
scanf("%d%d%d", &year, &month, &day);
week = dayOfWeek(year, month, day);
printf("%d年%d月%d日是%s\n", year, month, day,
week == 0 ? "星期日" : week == 1 ? "星期一" : week == 2 ? "星期二" :
week == 3 ? "星期三" : week == 4 ? "星期四" : week == 5 ? "星期五" : "星期六");
} else if (choice == 2) {
printf("请输入年月,用空格分隔:");
scanf("%d%d", &year, &month);
printMonth(year, month);
} else if (choice == 3) {
printf("请输入年份:");
scanf("%d", &year);
printYear(year);
} else if (choice == 4) {
break;
} else {
printf("输入无效,请重试\n");
}
}
return 0;
}
```
该程序实现了输入年月日,计算相应日期是星期几;输入年月,输出相应月份的日历;输入年份,输出该年所有日历;具有退出功能。其中,`dayOfWeek`函数计算某一天是星期几,`isLeap`函数判断是否为闰年,`printMonth`函数输出某年某月的日历,`printYear`函数输出某年的所有日历。在主函数中,通过循环实现了不断选择功能的操作。
阅读全文