C语言:定义函数给出任意一天对应是星期几
时间: 2024-03-21 10:18:08 浏览: 78
判断任意一天是星期几
5星 · 资源好评率100%
以下是一个例子:
```c
#include <stdio.h>
int dayOfWeek(int y, int m, int d) {
// Zeller's congruence algorithm
if (m < 3) {
y--;
m += 12;
}
int c = y / 100;
y %= 100;
int w = (c / 4) - (2 * c) + ((y + (y / 4)) + ((13 * (m + 1)) / 5) + d - 1);
return ((w % 7) + 7) % 7;
}
int main() {
int year, month, day;
printf("Enter the year, month, and day: ");
scanf("%d %d %d", &year, &month, &day);
int dayOfWeekNumber = dayOfWeek(year, month, day);
switch (dayOfWeekNumber) {
case 0:
printf("Sunday\n");
break;
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
}
return 0;
}
```
在这个例子中,我们使用了 Zeller's congruence 算法来计算星期几。用户输入年、月、日后,我们调用 `dayOfWeek` 函数来得到星期几的数字,然后使用 `switch` 语句来打印对应的星期几字符串。
阅读全文