题解 | #打印日期#
打印日期
https://www.nowcoder.com/practice/b1f7a77416194fd3abd63737cdfcf82b
#include <iomanip> #include <iostream> #include <istream> #include <ostream> using namespace std; class Date { //输入流和输出流 //friend istream& operator>>(iostream& in,Date& d); friend ostream& operator<<(ostream& on,const Date& d); public: //构造函数 Date(int year=2000,int month = 1,int day = 0) :_year(year) ,_month(month) ,_day(day) {} //获取天数 static int GetMonthDay(int year,int month ,int day ) { static int MonthDay[13]={-1,31,28,31,30,31,30,31,31,30,31,30,31}; //如果是闰年返回29 if((month == 2) && ((year % 400 == 0) || (year % 100 != 0 && year % 4 == 0 ))) { return 29; } return MonthDay[month]; } //+=的实现 Date& operator+=(int day) { _day+=day; while (_day>GetMonthDay(_year,_month,_day)) { _day-=GetMonthDay(_year,_month,_day); ++_month; if(_month > 12) { _month=1; ++_year; } } return *this; } private: int _year; int _month; int _day; }; ////输入流和输出流 //istream& operator>>(iostream& in,Date& d) //{ // in >> d._year >> d._month >> d._day; // return in; //} ostream& operator<<(ostream& on,const Date& d) { on <<setw(4)<<setfill('0') <<d._year <<"-" <<setw(2)<<setfill('0')<< d._month <<"-" <<setw(2)<<setfill('0')<< d._day << endl; return on; } int main() { int year;int day; while (cin>>year>>day) { Date A(year); A+=day; cout<<A; } return 0; }
https://blog.csdn.net/Jason_from_China/article/details/142516352
这里本质上还是日期类的实现,没有什么难度,但是有两点注意事项
1,构造函数这里,我们初始化的时候,day=0,Date(int year=2000,int month = 1,int day = 0)
2,对齐的时候需要用一个库函数,printf在这里会更好使一点
3,思路:这里就等于 【2000(年),1(月份),0(天数)】+100(天数)=日期。所以我们只需要输入年,构造解决好就可以