题解 | #日期累加#
日期累加
https://www.nowcoder.com/practice/eebb2983b7bf40408a1360efb33f9e5d
#include <iostream>
using namespace std;
class Date{
private:
size_t _year;
size_t _month;
size_t _date;
public:
Date(const size_t year,const size_t month,const size_t date)
:_year(year)
,_month(month)
,_date(date)
{}
int Day(size_t 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))
{
arr[2]=29;
}
return arr[month];
}
void addDate(int i)//计算日期
{
_date+=i;
while(_date>Day(_month))
{
_date-=Day(_month);
_month++;
if(_month>12)
{
_year++;
_month=1;
}
}
//输出
if(_month<10&&_date<10)
{
cout<<_year<<"-0"<<_month<<"-0"<<_date<<endl;
}
else if(_month<10)
{
cout<<_year<<"-0"<<_month<<"-"<<_date<<endl;
}
else if(_date<10)
{
cout<<_year<<"-"<<_month<<"-0"<<_date<<endl;
}
else
cout<<_year<<'-'<<_month<<'-'<<_date<<endl;
}
};
int main()
{
int i=0;
cin>>i;
while(i--)
{
size_t y,m,d,num;
cin>>y>>m>>d>>num;
Date day(y,m,d);
day.addDate(num);
}
return 0;
}
阿里云工作强度 710人发布
