题解 | #打印日期#
打印日期
https://www.nowcoder.com/practice/b1f7a77416194fd3abd63737cdfcf82b
#include <climits> #include <iostream> using namespace std; class Date { public: friend ostream& operator<<(ostream& out, const Date& d); Date(int year, int month, int day); int GetMonthDay(int year, int month); Date& operator+=(int day); private: int _year; int _month; int _day; }; Date::Date(int year, int month, int day) { _year = year; _month = month; _day = day; } Date& Date::operator+=(int day) { _day += day; while (_day > GetMonthDay(_year, _month)) { _day -= GetMonthDay(_year, _month); ++_month; if (_month == 13) { _year++; _month = 1; } } return *this; } int Date::GetMonthDay(int year, int month) { static int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int day = days[month]; if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))) { day += 1; } return day; } 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; } void TestDate1() { int year = 0, month = 1, day = 0; int n = 0; while(cin>>year>>n) { Date d(year,month,day); d+=n; cout<<d<<endl; } } int main() { TestDate1(); return 0; }