c语言编写程序计算日期是当年的第几天 定义一个结构体变量(包括年、月、日)。计算该日在本年中是第几天,注意闰年问题
时间: 2024-06-14 18:04:54 浏览: 87
C语言 结构体
```c
#include <stdio.h>
struct Date {
int year;
int month;
int day;
};
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return 1;
} else {
return 0;
}
}
int calculateDayOfYear(struct Date date) {
int daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int dayOfYear = 0;
for (int i = 1; i < date.month; i++) {
dayOfYear += daysInMonth[i];
}
dayOfYear += date.day;
if (isLeapYear(date.year) && date.month > 2) {
dayOfYear += 1;
}
return dayOfYear;
}
int main() {
struct Date date;
printf("请输入日期(年 月 日):");
scanf("%d %d %d", &date.year, &date.month, &date.day);
int dayOfYear = calculateDayOfYear(date);
printf("该日在本年中是第%d天\n", dayOfYear);
return 0;
}
```
阅读全文