.给出年、月、日,计算该日是该年的第几天。
#include <stdio.h>
// 判断闰年
int is_leap_year(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return 1;
} else {
return 0;
}
}
// 计算日期是当年的第几天
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};
if (is_leap_year(year)) {
days_in_month[1] = 29;
}
int day_of_year = 0;
for (int i = 0; i < month - 1; i++) {
day_of_year += days_in_month[i];
}
day_of_year += day;
return day_of_year;
}
int main() {
int year, month, day;
printf("输入年、月、日:");
scanf("%d %d %d", &year, &month, &day);
int result = day_of_year(year, month, day);
printf("这一天是这一年的第%d天\n", result);
return 0;
}
解释说明:
计算天数:
- 函数
is_leap_year
判断年份是否为闰年。 - 函数
day_of_year
根据输入的年月日计算该日期是当年的第几天。 - 主函数从键盘输入年、月、日,调用
day_of_year
函数并输出结果。