算法每日一题 23/6/08 日期差值(日期问题)

该代码实现了一个程序,用于计算两个日期之间的天数差。它考虑了平年和闰年的天数,并使用C++编写。程序首先定义了一个月份天数的数组,然后通过is_leap函数判断是否为闰年,get_month_days函数获取某月的天数,最后get_total_days函数计算指定日期前的所有天数。在主函数中,读入两个日期并输出它们之间的天数差。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AcWing 3498. 日期差值

原题链接

题目描述

在这里插入图片描述

代码实现

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;

const int months[]={
    0,31,28,31,30,31,30,31,31,30,31,30,31
};

int is_leap(int year)
{
    if((year%100&&year%4==0)||year%400==0)
        return 1;
    return 0;
}

int get_month_days(int year,int month)
{
    int res=months[month];
    if(month==2) return res+=is_leap(year);
    return res;
}

int get_total_days(int year,int month,int day)
{
    int res=0;
    for(int i=1;i<year;i++)
        if(is_leap(i)) res+=366;
        else res+=365;
    
    for(int i=1;i<month;i++)
        res+=get_month_days(year,i);
    
    res+=day;
    
    return res;
}

int main()
{
    int y1,m1,d1,y2,m2,d2;
    while(scanf("%04d%02d%02d",&y1,&m1,&d1)!=-1)
    {
        scanf("%04d%02d%02d",&y2,&m2,&d2);
        printf("%d\n",abs(get_total_days(y1,m1,d1)-get_total_days(y2,m2,d2))+1);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值