题目描述
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天。
- 输入描述:
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD - 输出描述:
每组数据输出一行,即日期差值
题解
基于日期类:
1.定义一个静态数组存放12个月每月对应的天数,其中2月默认为28天。若是闰年则2月为29天。
2.直接相减借位不太好实现。可以每次让较小的日期++,然后判断是否等于较大的日期,其中++的次数即为相差的天数。
3.注意题目描述(有点坑):如果两个日期是连续的我们规定他们之间的天数为两天,→ 返回相差日期时再加1。
#include<iostream>
using namespace std;
class Date{
private:
int _year;
int _month;
int _day;
public:
//获取当月天数
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%4==0 && year%100!=0) || year%400==0))
return 29;
return arr[month];
}
// <重载
bool operator<(const Date& d){
if(_year < d._year)
return true;
else if(_year==d._year && _month<d._month)
return true;
else if(_year==d._year && _month==d._month && _day<d._day)
return true;
return false;
}
// !=重载
bool operator!=(const Date& d){
if(_year==d._year && _month==d._month && _day==d._day)
return false;
return true;
}
// +=重载
Date& operator+=(int n){
_day+=n;
while(_day>GetMonthDay(_year, _month)){
_day-=GetMonthDay(_year, _month);
++_month;
if(_month==13){
++_year;
_month=1;
}
}
return *this;
}
//d1-d2 计算差值
int operator-(const Date& d){
Date max = *this;
Date min = d;
int different = 0; //差值
if (*this < d){
max = d;
min = *this;
}
while (min != max){
min+=1;
++different;
}
return different+1;
}
void Input(){
int year,month,day=0;
scanf("%4d%2d%2d", &year, &month, &day);
//判断输入是否为合法日期
if (year >= 0 && month >= 1 && month <= 12 && day >= 1 && day <= GetMonthDay(year, month)){
_year=year;
_month=month;
_day=day;
}
}
};
int main(){
Date d1;
d1.Input();
Date d2;
d2.Input();
cout<<(d1-d2)<<endl;
return 0;
}