编写一个C语言程序,编写一个计算星期几的函数,已知2019年1月1日是星期二,给出2019年 M月D日,首先判断日期是否合理,如果合理则给出星期几,否则给出错误信息。(请给出代码)
时间: 2024-05-11 22:15:45 浏览: 41
以下是实现该功能的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
int day_of_week(int year, int month, int day);
int main(void) {
int year, month, day;
printf("请输入日期(格式为 年 月 日,用空格隔开):");
if (scanf("%d %d %d", &year, &month, &day) != 3) {
printf("输入格式错误!\n");
return EXIT_FAILURE;
}
if (month < 1 || month > 12) {
printf("月份错误!\n");
return EXIT_FAILURE;
}
int days_in_month[] = {
31, (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 ? 29 : 28,
31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
if (day < 1 || day > days_in_month[month - 1]) {
printf("日期错误!\n");
return EXIT_FAILURE;
}
int day_of_week_number = day_of_week(year, month, day);
char *day_of_week_name[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
printf("%d-%d-%d 是 %s\n", year, month, day, day_of_week_name[day_of_week_number]);
return EXIT_SUCCESS;
}
int day_of_week(int year, int month, int day) {
int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
if (month < 3)
year -= 1;
return (year + year / 4 - year / 100 + year / 400 + t[month - 1] + day) % 7;
}
```
这个程序使用了蔡勒公式来计算给定日期是星期几,比较精确可靠。
阅读全文