qfedu-c-level/day12/homework/h5_2.c

74 lines
1.5 KiB
C
Raw Permalink Normal View History

2023-07-22 10:37:20 +08:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct date_s
{
int year;
int month;
int day;
} DATE;
int daysOfMonth(int year, int month)
{
switch (month)
{
case 2:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return 29;
else
return 28;
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
int sumDays(int year, int month, int day)
{
int sum = day;
for (int i = 1; i < month; i++)
{
sum += daysOfMonth(year, i);
}
return sum;
}
int yearOFdays(int year1, int year2)
{
int sum = 0;
int minYear = (year1 < year2) ? year1 : year2;
int maxYear = (year1 > year2) ? year1 : year2;
for (int i = minYear; i < maxYear; i++)
{
if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0)
sum += 366;
else
sum += 365;
}
return sum;
}
int main()
{
DATE day1, day2;
printf("请输入第一个日期,输入格式为 年,月,日 ");
scanf("%d,%d,%d", &day1.year, &day1.month, &day1.day);
printf("请输入第二个日期,输入格式为 年,月,日 ");
scanf("%d,%d,%d", &day2.year, &day2.month, &day2.day);
int sumdays1 = sumDays(day1.year, day1.month, day1.day);
int sumdays2 = sumDays(day2.year, day2.month, day2.day);
int yearMoreDays = yearOFdays(day1.year, day2.year);
int days = abs(sumdays1 - sumdays2) + yearMoreDays;
printf("两个日期的天数差为: %d", days);
return 0;
}