一年中任意两天的差值。输入N组数测试。(保证后一天日期晚于前一天日期)输出两个日期间的天数。
样例:
2019 1 1 2019 1 2
2016 1 1 2016 3 1
输出:
2
61
判断一年中任意两天的差值主要在于闰月的处理,和中间月份总天数处理。
#include<stdio.h> //一年中任意两天的差值
#include<string.h>
#define Elemtype int
//1 2 3 4 5 6 7 8 9 10 11 12
//31 28(29) 31 30 31 30 31 31 30 31 30 31
int prime[12] = {31,29,31,30,31,30,31,31,30,31,30,31};//闰年
int Notprime[12] = {31,28,31,30,31,30,31,31,30,31,30,31};//非闰年
struct date{
Elemtype year;
Elemtype month;
Elemtype day;
}Date;
int IsPrime(Elemtype Year)//判断闰年
{
if((Year%4==0&&Year%100!=0)||(Year%400==0))
return 1;
else
return 0;
}
int ComDate(struct date mindate,struct date maxdate)
{
Elemtype m = maxdate.month - mindate.month;
Elemtype n = maxdate.day - mindate.day + 1;
Elemtype sum = 0,i = 0;
if(IsPrime(mindate.year)){ //闰
for(i=mindate.month;i<=m;i++)
sum += prime[i-1];
sum += n;
}else{
for(i=mindate.month;i<=m;i++)
sum += Notprime[i-1];
sum += n;
}
return sum;
}
int main()
{
struct date Mindate;
struct date Maxdate;
/*Mindate.year = 2019; Mindate.month = 1; Mindate.day = 1; //下面是两组测试数据
Maxdate.year = 2019; Maxdate.month = 1; Maxdate.day = 2;*/
Mindate.year = 2016; Mindate.month = 1; Mindate.day = 1;
Maxdate.year = 2016; Maxdate.month = 3; Maxdate.day = 1;
printf("Date = %d\n",ComDate(Mindate,Maxdate));
return 0;
}
以下是两组数据分别测试的结果