日期差值。

acwing 3498

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

输入格式

输入包含多组测试数据。

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

输出格式

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

数据范围

年份范围 [1,9999][1,9999],
保证输入日期合法。
测试数据的组数不超过 100100。

输入样例:
20110412
20110422
输出样例:
11

 

#include<iostream>
#include<string>
using namespace std;

#include <stdlib.h>
const int month[] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };

int get_two(int year)
{
    if (year % 4 == 0 && year % 100 || year % 400 == 0)//闰年可以被4整除,不能被100整除
    {
        return 1;
    }
        
    return 0;
}
int get_month(int y, int m)//得到当前年份每个月的天数
{
    if (m == 2)return 28 + get_two(y);
    return month[m];
}
int leap(int y, int m, int d,int ans)//计算总天数
{
    for (int i = 1; i < y; i++)
    {
        ans += 365 + get_two(i);
    }
    for (int i = 1; i < m; i++)
    {
        ans += get_month(y,i);
    }
    
    return ans+d;
}
int main()
{
    string s, s1;
    
    while (cin >> s >> s1)
    {
        int ans = 0;
        //将输入的日期分开,分成 年 月 日
        string y1(s, 0, 4); string m1(s, 4, 2); string d1(s, 6, 2);
        string y2(s1, 0, 4); string m2(s1, 4, 2); string d2(s1, 6, 2);
        //将字符数组转换成整型 atoi(const char*[])
        // atof 字符串转换成double
        // c_str()可以将string转换成char*[]
        int a1 = atoi(y1.c_str()); int a2 = atoi(m1.c_str()); int a3 = atoi(d1.c_str());//将各个字符串转换成int类型
        int b1 = atoi(y2.c_str()); int b2 = atoi(m2.c_str()); int b3 = atoi(d2.c_str());
        //abs(int a)取a的绝对值
        //两个年份之间的差值可以看作两个年份从0001年01月01日到各个年份的总日期的差值
        cout << abs(leap(b1, b2, b3, ans) - leap(a1, a2, a3, ans))+1 << endl;
        
  }
        
    
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值