用c语言编写程序实现如下功能: 输入某年某月某日,判断这一天是这一年的第几天?
时间: 2024-12-11 20:33:42 浏览: 109
在C语言中,我们可以使用闰年规则来计算给定日期是一年中的第几天。这里提供一个简单的示例程序来实现这个功能:
#include <stdio.h>
int is_leap_year(int year) {
// 判断是否为闰年,如果能被4整除但不能被100整除,或者能被400整除,就是闰年
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int day_of_month(int month, int day, int year) {
switch(month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: // 月份有31天
return day;
case 4:
case 6:
case 9:
case 11: // 月份有30天
return day;
case 2: // 二月,需要考虑闰年
if (is_leap_year(year)) {
return day;
} else {
return day - 1; // 非闰年的二月只有28天
}
default: // 确保输入的月份在有效范围内
printf("Invalid month.\n");
return -1;
}
}
int main() {
int year, month, day;
printf("Enter the year, month, and day: ");
scanf("%d %d %d", &year, &month, &day);
// 检查输入的有效性
if (month <= 0 || month > 12 || day <= 0 || day > 31) {
printf("Invalid date.\n");
return 1;
}
int total_days = day_of_month(month, day, year);
if (total_days >= 0) {
printf("The given date, %d-%02d-%02d, is the %dth day of the year.\n", year, month, day, total_days + 1); // 加1是因为从1开始计数
}
return 0;
}
这个程序首先定义了一个辅助函数is_leap_year()
用于检查给定的年份是否是闰年。然后在day_of_month()
函数中根据月份计算给定日期是一年中的第几天。在主函数main()
中获取用户输入并调用这个函数。
相关推荐


















