codeup 1928求日期差值

题目描述

有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天。

输入格式

有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD

输出格式

每组数据输出一行,即日期差值

样例输入

20131001
20130105

样例输出

5

思路

分别计算两个日期与一个日期的差,两个差相减后+1即为答案。有一种简易做法,代码如下:

#include<stdio.h>
#include<math.h>
#define isRen(x) x % 4 == 0 && x % 100 != 0 || x % 400 == 0
struct Date{
    int year;
    int month;
    int day;
}left,right;

//计算与0000年1月1日的日期差,注意必须是0000年,否则这日期差从计算年数开始就可能算错 
long long getCha(Date date){  
    long long day=0;   
    //计算年数的日期差
    for(int i=0;i<dateR.year;i++){
        if(isRen(i)) day+=366;
        else day+=365;
    }
    //计算月数的日期差
    for(int i=1;i<date.month;i++){
        if(i==4||i==6||i==9||i==11){
            day+=30;
        }else{
            if(i==2){
                if(isRen(date.year)) day+=29;
                else day+=28;
            }else day+=31;
        }
    }
    //计算当月内的日期差
    day+=date.day;
    return day;   
}
int main(){
    while(scanf("%4d%2d%2d",&left.year,&left.month,&left.day)!=EOF){
        scanf("%4d%2d%2d",&right.year,&right.month,&right.day);
        long long chaleft=getCha(left);
        long long charight=getCha(right);
        if(chaleft>charight) printf("%lld\n",chaleft-charight+1);
        else printf("%lld\n",charight-chaleft+1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值