[Data Structure Algorithm Notes]----date difference processing (leap year processing in normal years, big month and small month processing, number of days in February)

Title description: There are two dates, find the number of days between the two dates, if the two dates are consecutive, specify the number of days between them as two days. Input format: YYYYMMDD

Specific ideas: Let's assume that the first date is earlier than the second date (otherwise just swap). This question of finding the difference in days between dates has a very direct idea, that is, adding 1 day to the date until the first date is equal to the second date, and then the answer can be calculated. During the specific processing, if the number of days d is equal to the number of days owned by the current month m plus 1 after adding one day, then the month m is added by 1, and the number of days d is set as 1 at the same time (that is, the date is changed to the 1st of the next month ); If the month m becomes 13 at this time, then the year y is increased by 1, and the month m is set to January at the same time (that is, the date is changed to January of the next year).
      In order to directly retrieve the number of days in each month, a two-dimensional array int month[13][2] may be given to store the number of days in each month. When the second dimension is 0, it means an ordinary year, and when it is 1, it means a leap year .


Note: If you want to speed up, you only need to add 1 to the year of the first date until it is 1 different from the year of the second date. During this period, add 365 or 366 days according to the normal year or leap year. Then continue to add 1 to the number of days.


#include<stdio.h>
int mouth [13][2]={
   
   {0,0},{31,31},{28,29},{31,31},{30,30},{31,31},{30,30},
    {31,31},{31,31},{30,30},{31,31},{30,30},{31,31}}; /*初始值为0,{平年,闰年}的区别*/
bool isrun(int year){
    return (year%4==0&&year%100!=0)||(year%400==0);}/*判断某年是否为闰年,返回bool值*/ 
int main(){
	int y1,m1,d1;
	int y2,m2,d2;
	int time1,time2;
	while(scanf("%d%d",&time1,&time2)!=EOF){/*输入的值正确,才进行以下操作*/
	  
		if(time1>time2){  /*因为计算差值是day+1的方式,则time1必须小于time2*/
	    	int t=time1;
	    	time1=time2;
	    	time2=t;
		} 
	    y1=time1/10000,m1=time1%10000/100,d1=time1%100;/*将年月日分开取出来*/
		y2=time2/10000,m2=time2%10000/100,d2=time2%100;
		int ans=1;                                     /*看题*/
		while(!((y1==y2)&&(m1==m2)&&(d1==d2))){
			d1++;
			if (d1==mouth[m1][isrun(y1)]+1){/*日期满了进一,月份满了进一*/
				m1++;
				d1=1;	}
			if (m1==13){y1++;m1=1;}
			ans++;
		} 
        printf("%d",ans);
    }
	return 0; 	
}

 

Guess you like

Origin blog.csdn.net/weixin_51538341/article/details/125369081