计算任意两个日期之间的天数问题

 程序代码:

#include  " stdio.h "

int  days[ 2 ][ 13 ] = {365,31,28,31,30,31,30,31,31,30,31,30,31,
                
366,31,29,31,30,31,30,31,31,30,31,30,31}
;

int  Leap( int  year)         // 判断是否为闰年
{
    
return ( (year%400==0|| (year%4==0 && year%100!=0));
}


int  Deal( int  dat0, int  dat1)
{
    
int i,temp,sum0,sum;
    
int year0,month0,day0,year1,month1,day1;
    sum0 
= sum = 0;
    year0 
= dat0/10000;    month0 = dat0/100%100;    day0 = dat0%100;
    year1 
= dat1/10000;    month1 = dat1/100%100;    day1 = dat1%100;

    
/*************************************************************/
    
/* 在起始日期和终止日期在同一年                                         */
    
/*************************************************************/
    
if((year1-year0)==0)
    
{
        
if((month1-month0)==0)
            
return (day1-day0);
        
else
        
{
            temp 
= Leap(year0);
            sum 
= days[temp][month0] - day0 +1;
            
for(i=month0+1;i<=month1-1;i++)
                sum 
= sum + days[temp][i];
            sum 
=sum + day1;
            
return sum;
        }
        
    }


    
/************************************************************************/
    
/* 在起始日期和终止日期不在同一年                                       */
    
/************************************************************************/
    
//计算开始年剩余的天数
    temp = Leap(year0);
    sum0 
= sum0 + (days[temp][month0] - day0) + 1;
    
for (i=month0+1; i<=12; i++)
        sum0 
= sum0 + days[temp][i];
    
    sum 
= sum +sum0;
    sum0 
= 0;

    
//计算中间年份的总天数
    for (i=year0+1;i<=year1-1;i++)
    
{
        temp 
= Leap(i);
        sum 
= sum + days[temp][0];
    }


    
//计算结束年过去的天数
    temp = Leap(year1);
    
for(i=1;i<=month1-1;i++)
        sum0 
= sum0 + days[temp][i];
    sum0 
= sum0 + day1;

    sum 
= sum + sum0;

    
return sum;
}


void  main()
{
    
int dat0,dat1,sum;
    FILE 
*fp = NULL;
    
if(fp = fopen("riqi.dat","r"))
    
{
        
while (fscanf(fp,"%d%d",&dat0,&dat1)==2)
        
{
            
if(dat0==0 && dat1==0)    break;
            sum 
= Deal(dat0,dat1);
            printf(
"天数为:%d ",sum);
        }

    }

    fclose(fp);
}

程序数据文件格式:

(日期格式为:年月日;年为任意位数,月、日的位数为两位,不足补零;两个日期中间以空格隔开;以下数据复制到记事本,重命名为“riqi.dat”,与代码文件放在同一文件夹)

  例:

19861231 19870101
19860101 19861231
19850101 19861231
19840101 19861231
19830101 19861231
19820101 19861231
19810101 19861231
2020811 19860606
0 0

 

运算结果:

天数为:2
天数为:365
天数为:730
天数为:1096
天数为:1461
天数为:1826
天数为:2191
天数为:651528
请按任意键继续. . .

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值