写一个函数days,
【定义一个结构体变量(包括年、月、日)。计算该日在本年中是第几天,注意闰年问题(即将闰年情况包含在内)】
由主函数将年、月、日传递给days函数,计算后将日子数传回主函数输出。
cpp
#include <stdio.h>
typedef struct {
int year;
int month;
int day;
} Date;
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return 1;
return 0;
}
int daysOfMonth(int month, int year) {
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && isLeapYear(year))
return 29;
return days[month - 1];
}
int dayOfYear(Date date) {
int days = 0;
for (int i = 1; i < date.month; i++) {
days += daysOfMonth(i, date.year);
}
days += date.day;
return days;
}
int main() {
Date date;
printf("Enter year, month, day: ");
scanf("%d %d %d", &date.year, &date.month, &date.day);
int day = dayOfYear(date);
printf("The day is the %dth day of the year.\n", day);
return 0;
}
[点击并拖拽以移动]
程序实现
cpp
#include <stdio.h>
typedef struct {
int year;
int month;
int day;
} Date;
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return 1;
return 0;
}
int daysOfMonth(int month, int year) {
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && isLeapYear(year))
return 29;
return days[month - 1];
}
int days(Date date) {
int days = 0;
for (int i = 1; i < date.month; i++) {
days += daysOfMonth(i, date.year);
}
days += date.day;
return days;
}
int main() {
Date date;
printf("Enter year, month, day: ");
scanf("%d %d %d", &date.year, &date.month, &date.day);
int day = days(date);
printf("The day is the %dth day of the year.\n", day);
return 0;
}
代码解释:
-
定义 `days` 函数:编写 `days` 函数,实现第1题的计算逻辑。该函数接受年、月、日作为参数,并返回该日期在一年中的第几天。
-
主函数调用:在主函数中,读取用户输入的年、月、日,并调用 `days` 函数计算天数,最后将结果输出。