问题描述
描述
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天。
输入描述:
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD
输出描述:
每组数据输出一行,即日期差值
示例
输入:
20110412
20110422
输出:
11
问题分析
这是一个处理分析问题。
解决方案
我们只需要算出输入的日期距最早的的年份总共多少天即可;
小问题1:我们怎么计算出距离天数?
答:我们可以通过最早的那一年的第一天距离两个日期的天数之和作为计算对象;
小问题2?怎么计算上述天数?
答:实现天数计算函数即可——实现两个函数分别计算平年闰年的月天数和年天数;
代码
//思路:我们只需要算出输入的日期距最早的的年份总共多少天即可
#include <iostream>
using namespace std;
int GetMonthDay(int year, int month) //得到一个月的月数
{
const static int day_arr[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month == 2
&& (year % 4 == 0 && year % 100 != 0 || (year % 400 == 0))
) {
return 29;
}
return day_arr[month];
}
int GetYearhDay(int year) //得到一个年的月数
{
if (year % 4 == 0 && year % 100 != 0 || (year % 400 == 0))
return 366;
else
return 365;
}
int MonthSum(int year, int month, int day) //得到不满一年的月数总天数
{
int sum = 0;
for (int i = 1; i < month; i++)
{
sum += GetMonthDay(year, i);
}
return sum + day;
}
int SumDay(const int date1, const int date2)
{
int max = 0;
int min = 0;
//找到较大的日期max
if (date1 > date2)
{
max = date1;
min = date2;
}
else {
max = date2;
min = date1;
}
int ret_day1 = 0;
int ret_day2 = 0;
//返回的天数即为两个日期的差
//年日期差
while ((max / 10000) != (min) / 10000)
{
ret_day1 = GetYearhDay(date1 / 10000);
max -= 10000;
}
ret_day2 += MonthSum(min / 10000, (min % 10000) / 100, min % 100);
ret_day1 += MonthSum(max / 10000, (max % 10000) / 100, max % 100);
return ret_day1 - ret_day2 + 1;
}
int main() {
int date1;
int date2;
cin >> date1;
cin >> date2;
cout << SumDay(date1, date2);
}