求两天相距的天数

输入某两天的年月日,输出这两天的相距多少天。

解:计算两个日期到后一个日期最后一天的天数,相减即可。

 1 #include<stdio.h>
 2 
 3 #define LEAPYEAR 366 //闰年
 4 #define COMMONYEAR 365 //平年
 6 
 7 int month_day[14] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
 8 
 9 int isLeapyear(int year)
10 {
11     return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))? 1 : 0;
12 }
13 
14 int get_day(int year, int month, int day)
15 {
16     int res_postyear_day = 0;
17     if (!isLeapyear(year)) {
18         for (int i = month + 1; i <= 12; i++)
19             res_postyear_day += month_day[i];
20         res_postyear_day += month_day[month] - day + 1;
21     }
22     else {
23         if (month <= 2) month_day[2] = 29;
24         for (int i = month + 1; i <= 12; i++)
25         {
26             res_postyear_day += month_day[i];
27         }
28         res_postyear_day += month_day[month] - day + 1;
29     }
30     return res_postyear_day;
31 }
32 
33 
34 
35 int main() {
36 
37     int pre_year, pre_month, pre_day;
38     int post_year, post_month, post_day;
39     printf("输入第一个日期:");
40     scanf("%d%d%d", &pre_year, &pre_month, &pre_day);
41     printf("输入第二个日期:");
42     scanf("%d%d%d", &post_year, &post_month, &post_day);
43     
44     int post_res = get_day(post_year, post_month, post_day);//求出后一个日期距该年底的天数
45     int pre_res = get_day(pre_year, pre_month, pre_day);//求出前一个日期距该年底的天数
46     
47     int ans=0;
48     if (pre_year == post_year) ans = pre_res - post_res;//如果是同一年,直接相减
//如果中间有相隔年份,按整年计算
49 else { 50 for (int i = pre_year + 1; i <= post_year; i++) 51 { 52 if (isLeapyear(i))pre_res += LEAPYEAR; 53 else pre_res += COMMONYEAR; 54 } 55 ans = pre_res - post_res; 56 } 57 58 printf("两个日期相差:%d 天", ans); 59 60 return 0; 61 }

 

posted @ 2024-04-24 16:53  Uiney  阅读(17)  评论(0编辑  收藏  举报