码迷,mamicode.com
首页 > 其他好文 > 详细

求两日期之间的相隔天数(year,month,day)

时间:2015-04-06 17:17:15      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:


主要思路理解部分看ppt


#include<cstdio>
int isRunNian(int year);
int DiJiTian(int year,int month,int day);
void swap(int *a,int *b);
int main()
{
	int year1,month1,day1;
	int year2,month2,day2;
	int sum=0;
	scanf("%d%d%d",&year1,&month1,&day1);
	scanf("%d%d%d",&year2,&month2,&day2);
	if(year1==year2)
	{
		sum = DiJiTian(year1,month1,day1) - DiJiTian(year2,month2,day2); 
		if(sum<0)
			sum=-sum;
	}
	else
	{
		if(year1 > year2)
		{
			swap(&year1,&year2);
			swap(&month1,&month2);
			swap(&day1,&day2);
		}
		int a,b,c;
		if(isRunNian(year1))
			a=366-DiJiTian(year1,month1,day1);
		else
			a=365-DiJiTian(year1,month1,day1);
		
		b=0;
		int i;
		for(i=year1+1;i<year2;i++)
		{
			if(isRunNian(i))
				b+=366;
			else
				b+=365;
		}
		
		c=DiJiTian(year2,month2,day2);
		
		sum=a+b+c;
	}
	
	printf("%d\n",sum);
	return 0;
}



/*判断闰年的函数*/
int isRunNian(int year)
{
	if(year%400==0||(year%4==0&&year%100!=0))
		return 1;
	else
		return 0;
} 

/*判断这一天是这一年的第几天函数*/
int DiJiTian(int year,int month,int day)
{
	int i,sum=0;
	for(i=1;i<month;i++)//step1
	{
		if(i==1||i==3||i==5||i==7||i==8||i==10||i==12)
			sum+=31;
		else if(i==4||i==6||i==9||i==11)
			sum+=30;
		else if(i==2)
		{
			if(isRunNian(year))
				sum+=29;
			else
				sum+=28;
		}
	}
	sum+=day;//step2
	return sum;//step3
}

/* 交换两个变量的值的函数 */
void swap(int *a,int *b)
{
	int c;
	c=*a;
	*a=*b;
	*b=c;
} 


求两日期之间的相隔天数(year,month,day)

标签:

原文地址:http://blog.csdn.net/qq_16767427/article/details/44903293

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!