03_日期差值

题目描述

有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天。

  • 输入描述:
    有多组数据,每组数据有两行,分别表示两个日期,形式为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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值