点击链接即可查看题目:日期差值_牛客题霸_牛客网
一、 题目
描述
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天
输入描述:
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD
输出描述:
每组数据输出一行,即日期差值
示例1
输入:
20110412 20110422
输出:
11
二、 代码
#include <cstdio>
#include<iostream>
using namespace std;
bool IsLeapYear(int year)
{
return (year%4==0&&year%100!=0)||(year%400==0);
}
int daytab[2][13]={
{0,31,28,31,30,31,30,31,31,30,31,30,31},
{0,31,29,31,30,31,30,31,31,30,31,30,31}
};
int calDays(int min_year,int year,int month,int day)
{
int all_days=0;
for(int i=min_year;i<year;i++)
{
if(IsLeapYear(i)){
all_days+=366;
}
else all_days+=365;
}
if(IsLeapYear(year)){
for(int j=1;j<month;j++)
{
all_days+=daytab[1][j];
}
}
else{
for(int j=1;j<month;j++)
{
all_days+=daytab[0][j];
}
}
all_days+=day;
return all_days;
}
int main()
{
int year1,month1,day1,year2,month2,day2;
scanf("%4d%2d%2d",&year1,&month1,&day1);
scanf("%4d%2d%2d",&year2,&month2,&day2);
int min_year=min(year1,year2);
int all_day1=calDays(min_year,year1,month1,day1);
int all_day2=calDays(min_year,year2,month2,day2);
cout<<abs(all_day1-all_day2)+1;
return 0;
}