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

78 lines
1.9 KiB
C
Raw Normal View History

2023-07-22 10:37:20 +08:00
// 1. 2. 编写一个程序,定义一个结构体表示日期,包括年、月和日。编写一个函数,接受两个日期作为参数,并计算并返回它们之间的天数差。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct date_s
{
int year;
int month;
int day;
} DATE;
int sumDays(int year, int month, int day)
{
int sum = day;
switch (month)
{
case 12:
sum += 30;
case 11:
sum += 31;
case 10:
sum += 30;
case 9:
sum += 31;
case 8:
sum += 31;
case 7:
sum += 30;
case 6:
sum += 31;
case 5:
sum += 30;
case 4:
sum += 31;
case 3:
sum += 28;
case 2:
sum += 31;
}
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
sum += 1;
return sum;
}
int yearOFdays(int year1, int year2)
{
int sum = (abs(year1 - year2) - 1) * 365;
int runYearCount = 0; // 闰年计数器
int minYear = (year1 < year2) ? year1 : year2; // 找出较小的年份
int maxYear = (year1 > year2) ? year1 : year2; // 找出较大的年份
for (; minYear <= maxYear; minYear++)
if ((minYear % 4 == 0 && minYear % 100 != 0) || minYear % 400 == 0)
runYearCount++;
sum += runYearCount; // 每多一个闰年多一天
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;
}