c language calculates the number of days between two dates

1. Title Description

There are two dates, find the number of days between two dates, if two consecutive dates, the number of days to two days

2. Sample

20110412

20110422

11

3. Code Thought: date structure configured pretreatment, the date obtained by subtracting the first year of a fixed date difference, a difference between each corresponding to the date, the difference between the two dates is about their mutual subtraction, time complexity lower

#include<stdio.h>
#define ISYEAR(x) x % 100 != 0 && x % 4 ==0 || x % 400 ==0 ? 1 :0
int dayofmonth[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};
typedef struct Date{
    int Day;
    int Month;
    int yesr;
};
int buf[5001][13][32];
int Abs(int x)
{
    return x > 0 ? x : -x;
}
int main(){
	Date tmp;
	int cnt = 0;
	tmp.Day=1;
	tmp.Month = 1;
	tmp.year = 0;
	while(tmp.year != 5001){  //预处理,形成一个以年月份为下标的数组 
		bufday[tmp.year][tmp.Month][tmp.Day] = cnt;
		tmp.Day ++;
		if(tmp.Day >dayofmonth[tmp.Month][ISYEAR(tmp.year)]){
			tmp.Day = 1;
			tmp.Month ++;
			if(tmp.Month>12){
				tmp.Month = 1;
				tmp.year ++;
			}
		}
		cnt ++;
	}
	int d1,m1,y1;
	int d2,m2,y2;
	while(scanf("%4d%2d%2d",&y1,&m1,&d1)!= EOF){
		scanf("%4d%2d%2d",&y2,&m2,&d2);
		printf("%d\n",Abs(bufday[y1][m1][d1]-bufday[y2][m2][d2])+1);
	} 
	return 0;
}

 

Released two original articles · won praise 1 · views 572

Guess you like

Origin blog.csdn.net/qq_39750926/article/details/99681552