定义一个结构体变量包括年月日,编写一个程序计算当天在本年中是第几天,注意闰年问题。
要计算一个特定日期在一年中的第几天,需要考虑闰年的情况。
闰年是:1、指能够被4整除的年份,2、不能被100整除而能被400整除的年份。
#include <stdio.h>
// 定义日期结构体
typedef struct {
int year;
int month;
int day;
} Date;
// 函数声明
int isLeapYear(int year);
int dayOfYear(Date date);
int main() {
Date today;
// 获取用户输入的日期
printf("请输入日期(年 月 日): ");
scanf("%d %d %d", &today.year, &today.month, &today.day);
// 计算并输出结果
int dayNumber = dayOfYear(today);
printf("%d年%d月%d日是该年的第%d天。\n", today.year, today.month, today.day, dayNumber);
return 0;
}
// 判断是否为闰年的函数
int isLeapYear(int year) {
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
// 计算日期在一年中的第几天的函数
int dayOfYear(Date date) {
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int dayCount = 0;
// 如果是闰年,2月份天数为29天
if (isLeapYear(date.year)) {
daysInMonth[1] = 29;
}
// 累加从年初到当前月份的天数
for (int i = 0; i < date.month - 1; i++) {
dayCount += daysInMonth[i];
}
// 加上当前月份的天数
dayCount += date.day;
return dayCount;
}