Codeup[10000057]日期差值[解法三]

再之前我们介绍了2种计算日期差值的方法,最后我们来介绍另外1种方式。
其思路主要是将输入的日期转换为与公元1年相隔的日期总数,然后用2个日期数相减,从而得到两者之间相隔的天数。
下面是实现的代码:

#include <stdio.h>
#include <math.h>

int isLeap(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int get_days(int year, int month, int day) {
    int months[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int total = day - 1;
    int b = isLeap(year);
    year--;
    int k = year / 4 - year / 100 + year / 400;
    total += (year - k) * 365 + k * 366;
    for (int i = 1; i < month; ++i) {
        total += months[i];
    }
    // 补上一天
    if (month > 2 && b > 0) {
        total += 1;
    }
    return total;
}

int main() {
    int year, month, day;
    while (scanf("%4d%2d%2d", &year, &month, &day) != EOF) {
        int d1 = get_days(year, month, day);
        scanf("%4d%2d%2d", &year, &month, &day);
        int d2 = get_days(year, month, day);
        printf("%d\n", abs(d2 - d1)+1);
    }
}

对于1个输入的年,我们计算到该年为止一共有多少个闰年,将其存储在变量k中。
然后使用输入的年减去闰年的数从而得到平年的年数,将其乘以365天,再与闰年的数量相乘后相加从而得到最终年的总天数。
最后是对月份及天数的累加,从而得到最终间隔的天数。
这种方式实际上跟解法二执行效率没有太大的差别,执行速度会稍微快点,因为避免了排序及循环月份遍历的过程。
最后是通过后的结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值