如何用C语言编程来计算并确定给定日期是星期几?
时间: 2024-11-06 21:21:33 浏览: 79
在C语言中,可以利用蔡勒公式(Zeller's congruence)来计算任意日期的星期几。这是一种基于模运算的算法。以下是计算步骤:
```c
#include <stdio.h>
int getDayOfWeek(int year, int month, int day) {
if (month <= 2) {
month += 12;
year--;
}
int century = year / 100;
int weekDay = (day + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400) % 7;
// 星期天对应值为0
return (weekDay + 7) % 7; // 如果结果小于0,加7相当于回到上一周
}
int main() {
int year, month, day;
printf("请输入年份、月份和日期:");
scanf("%d %d %d", &year, &month, &day);
int result = getDayOfWeek(year, month, day);
switch (result) {
case 0: printf("星期日"); break;
case 1: printf("星期一"); break;
case 2: printf("星期二"); break;
case 3: printf("星期三"); break;
case 4: printf("星期四"); break;
case 5: printf("星期五"); break;
case 6: printf("星期六"); break;
}
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)