1.题目:
2.分析:
1. 分别求出每一个日期与0000年0月1日距离的天数
2. 两个距离天数相减即可得到两个日期相差的天数
3.我的代码:
#include <iostream>
using namespace std;
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
: _year(year)
, _month(month)
, _day(day) {}
// 获取天数
inline int GetMonthDay(int year, int month)
{
static int arr[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if ((month == 2) && ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))))
{
return 29;
}
else
{
return arr[month];
}
}
bool IsSame(Date& date)
{
return this->_year == date._year
&& this->_month == date._month
&& this->_day == date._day;
}
void Gap(int year, int month, int day)
{
int n = 1;
Date date(year, month, day);
while (IsSame(date) == false)
{
n++;
_day++;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
++_month;
if (_month > 12)
{
_month -= 12;
++_year;
}
}
}
cout << n << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
int year1 = 0;
int month1 = 0;
int day1 = 0;
int year2 = 0;
int month2 = 0;
int day2 = 0;
char arr1[9];
char arr2[9];
cin >> arr1 >> arr2;
sscanf(arr1,"%4d%2d%2d",&year1,&month1,&day1);//格式化读入
sscanf(arr2,"%4d%2d%2d",&year2,&month2,&day2);
Date date(year1, month1, day1);
date.Gap(year2, month2, day2);
}
4.答案代码:
#include <iostream>
using namespace std;
/*
*思路:
* 1. 分别求出每一个日期与0000年0月1日距离的天数
* 2. 两个距离天数相减即可得到两个日期相差的天数
*/
//平年从1月到n月的天数
int mon[12]={0,31,59,90,120,151,181,212,243,273,304,334};
//给出年月日,计算距离0000年0月1日的天数和
int CountDay(int y,int m,int d)
{
// 计算0-y年的天数
int yearDay = y*365+y/4-y/100+y/400;
// 计算到0-m月的天数
int monthDay = mon[m-1];
if(m > 2 && ((y%4 == 0 && y%100 != 0) || y%400==0))
monthDay += 1;
return yearDay + monthDay + d;
}
int main()
{
int year1,month1,day1;
scanf("%4d%2d%2d",&year1,&month1,&day1);
int n1 = CountDay(year1,month1,day1);
int year2,month2,day2;
scanf("%4d%2d%2d",&year2,&month2,&day2);
int n2 = CountDay(year2,month2,day2);
cout<<abs(n1-n2)+1<<endl;
}