定义一个结构体变量(包括年、月、日)。计算该日在本年中是第几天。输入年月日,输出当年第几天。请用c语言编写代码
时间: 2023-12-26 07:28:04 浏览: 146
以下是用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 getDayOfYear(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", &date.year);
printf("请输入月份:");
scanf("%d", &date.month);
printf("请输入日期:");
scanf("%d", &date.day);
int dayOfYear = getDayOfYear(date);
printf("该日在本年中是第%d天。\n", dayOfYear);
return 0;
}
```
阅读全文