输入年月日,输出该日是该年的第几天
时间: 2024-10-09 22:15:14 浏览: 46
要计算给定日期是一年中的第几天,我们可以使用蔡勒公式(Zeller's congruence),这是一个古老的算法,用于根据格里高利历(公历)快速确定某一天是当年的第几天。以下是一个简单的C语言函数实现了这个计算:
```c
#include <stdio.h>
int zeller(int year, int month, int day) {
if (month < 3) {
month += 12;
year--;
}
int q = day;
int m = month;
int k = year % 100;
int j = year / 100;
return (q + ((13 * (m + 1)) / 5) + k + (k / 4) + (j / 4) - (2 * j)) % 7;
}
int day_of_year(int year, int month, int day) {
int days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int total_days = 0;
for (int i = 1; i < month; i++) {
total_days += days_in_month[i];
}
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { // Leap year check
total_days++;
}
total_days += day;
return total_days;
}
int main() {
int year, month, day;
printf("Enter the year, month, and day (in that order): ");
scanf("%d %d %d", &year, &month, &day);
int day_num = day_of_year(year, month, day);
printf("The date %d-%d-%d is the %dth day of the year.\n", day, month, year, day_num);
return 0;
}
```
`zeller` 函数返回的是星期几(0表示星期日,1表示星期一,以此类推),而 `day_of_year` 函数则计算出指定日期是一年中的第几天。请注意,闰年的判断条件适用于格里高利历。
阅读全文