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;
}