.N天以后

编译器:C++ (g++)

改造练习13-1(日复一日)中的Date类并提交,使其可以与一个整数n相加或相减,得到该日期N天后/前的日期。

提示:

输入样例:

2022 8 31

2

说明:意为求2022年8月31日的后两天和前两天的日期。

输出样例:

2022-8-31 + 2 = 2022-9-2

2022-8-31 - 2 = 2022-8-29

请注意:函数题只需要提交相关代码片段,不要提交完整程序。
 

#include  <iostream>
#include  <string>
#include  <assert.h>
using  namespace  std;

//在此处补充Date类的定义
int  main()
{
        int  y,  m,  d;
        cin  >>  y  >>  m  >>  d;
        Date  d1(y,m,d);

        int  n;
        cin  >>  n;

        cout  <<  d1.toText()  <<  "  +  "  <<  n  <<  "  =  "  <<  (d1  +  n).toText()  <<  endl;
        cout  <<  d1.toText()  <<  "  -  "  <<  n  <<  "  =  "  <<  (d1  -  n).toText()  <<  endl;
        return  0;
}

Ans:


int daysInMonth[][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} 
                                                                        };

class Date {
private:
    int day;
    int month;
    int year;

public:

    Date(int y, int m, int d) :year(y), month(m), day(d) {

    }

    string toText() {
        string str = to_string(year) + "-" + to_string(month) + "-" + to_string(day);
        return str;
    }

    friend Date operator+(Date& a, int n);
    friend Date operator-(Date& a, int n);
};
bool isLeapyear(int y) {
    return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}

Date operator+(Date& a, int n) {
    Date tmp = a;
    for (int i = 0; i < n; i++) {
        int flag = 0;
        if (isLeapyear(tmp.year)) {
            flag = 1;
        }
        tmp.day++;
        if (tmp.day > daysInMonth[flag][tmp.month]) {
            tmp.day = 1;
            tmp.month++;
            if (tmp.month > 12) {
                tmp.year++;
                tmp.month = 1;
            }
        }
    }
    return tmp;
}

Date operator-(Date& a, int n) {
    Date tmp = a;
    for (int i = 0; i < n; i++) {
        int flag = 0;
        if (isLeapyear(tmp.year)) {
            flag = 1;
        }
        tmp.day--;
        if (tmp.day < 1) {
            tmp.day = daysInMonth[flag][--tmp.month];
            if (tmp.month < 1) {
                tmp.year--;
                tmp.month = 12;
            }
        }
    }
    return tmp;
}

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值