C_求两个日期相隔的天数(闰年)
1 #include <stdio.h> 2 #include <math.h> 3 4 int leap_year(int year){ 5 if(year%400==0 || (year%4==0 && year%100!=0)){ 6 return 1;//是闰年 7 }else{ 8 return 0;//不是闰年 9 } 10 } 11 12 int mon_d(int year,int mon){ 13 int i, days = 0,mon_days[12] = {31,28,31,30,31,30,31,31,30,31,30,31}; 14 //for(i=1;i<mon;i++){ 15 if(mon >= 2){ 16 if(leap_year(year) == 1){ 17 mon_days[1] = 29; 18 for(i=0; i<mon-1; i++){ 19 days += mon_days[i]; 20 } 21 return days; 22 }else{ 23 for(i=0;i < mon-1;i++){ 24 days += mon_days[i]; 25 26 } 27 return days; 28 } 29 } 30 //} 31 return 0; 32 } 33 34 int main(){ 35 36 int y1, m1, d1, y2, m2, d2, i, y, day_to_day = 0; 37 printf("请您输入一个日期(eg:2008-8-8): "); 38 39 scanf("%d-%d-%d",&y1,&m1,&d1); 40 41 printf("请您再输入一个日期(eg:2008-8-8): "); 42 scanf("%d-%d-%d",&y2,&m2,&d2); 43 //printf("%d-%d-%d\n",y1,m1,d1); 44 //printf("%d-%d-%d\n",y2,m2,d2); 45 46 y = y2-y1; 47 48 if(y == 0){ 49 day_to_day = mon_d(y2,m2) + d2 - (mon_d(y1,m1) + d1); 50 }else if(y == 1){ 51 day_to_day = 365 + leap_year(y1) - ( mon_d(y1,m1) + d1 ) + mon_d(y2,m2) +d2; 52 }else{ 53 for(i=y1+1; i<y2; i++){ 54 day_to_day += 365 + leap_year(i); 55 } 56 day_to_day += 365 + leap_year(y1) - ( mon_d(y1,m1) + d1 ) + mon_d(y2,m2) +d2;; 57 } 58 printf("这两个日期相差的天数是: %d 天\n",day_to_day); 59 60 }