题解 | #打印日期#

打印日期

https://www.nowcoder.com/practice/b1f7a77416194fd3abd63737cdfcf82b

#include <iostream>
using namespace std;

class Date
{
public:
    Date(int year = 2000, int month = 1, int day = 1)
        :_year(year)
        , _month(month)
        , _day(day)
    {

    }
    int GetMonthDay(int year, int month);
    //声明 
    //流插入 
    friend ostream& operator<<(ostream& out, const Date& d);
    Date operator+ (int n);
private:
    //声明 :成员变量 
    int _year;
    int _month;
    int _day;
};
int Date::GetMonthDay(int year, int month)
{
    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))

        //    if (      month == 2 && (      (year % 4 == 0 && year % 100 != 0) || year % 400 == 0     )         )
    {
        return 29;
    }
    else
    {
        return arr[month];
    }

}



ostream& operator<< (ostream& out, const Date& d)
{
    if (d._month < 10 && d._day < 10)
    {
        out << d._year << "-" << 0 << d._month << "-" << 0 << d._day;

    }
    else if (d._month >= 10 && d._day < 10)
    {
        out << d._year << "-" << d._month << "-" << 0 << d._day;

    }
    else if (d._month < 10 && d._day >=10)
    {

        out << d._year << "-" << 0 << d._month << "-" << d._day;

    }
    else
        out << d._year << "-" << d._month << "-" << d._day;
    return out;
}


Date Date::operator+ (int n)//50

//    Date Date::operator+ (Date *this , int n)
//计算天数到日期的转换 
{
    int year = _year; //2000
    int month = _month;//1
    int day = _day;//1
    int days = GetMonthDay(year, month);
    while(day + n > days)
    {
        //对month 进行操作
        month++;
        if (month == 13)
        {
            year++;
            month = 1;
        }
        n -= days;
        days = GetMonthDay(year, month);


    }
    //对day 进行操作 
    day += n;
    //匿名对象 
    return Date(year, month, day);


}

int main()
{
    int year, month, day = 0;
    int n = 0;
    while (cin >> year >> n)
    {
        Date d1(year, 1, 1); //假设year是2000,传参数为2000-1-1
        Date d2 = d1 + (n - 1);  //2000-1-1 +( n -1) 就是结果 
        cout << d2 << endl;
    }


    return 0;
}

全部评论
恰好我最近遇到这个,谢了兄弟
点赞 回复 分享
发布于 2023-05-26 20:54 黑龙江
楼主我辈楷模,这题解6啊
点赞 回复 分享
发布于 2023-05-26 20:18 湖北

相关推荐

门口唉提是地铁杀:之前b站被一个游戏demo深深的吸引了。看up主页发现是个初创公司,而且还在招人,也是一天60。二面的时候要我做一个登录验证和传输文件两个微服务,做完要我推到github仓库,还要我加上jaeger和一堆运维工具做性能测试并且面试的时候投屏演示。我傻乎乎的做完以后人家跟我说一句现在暂时不招人,1分钱没拿到全是白干
你的秋招第一场笔试是哪家
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务