C++ 累加天数(牛客网)
点击链接即可查看题目:日期累加_牛客题霸_牛客网
一、题目
描述
设计一个程序能计算一个日期加上若干天后是什么日期。
输入描述:
输入第一行表示样例个数m,接下来m行每行四个整数分别表示年月日和累加的天数。
输出描述:
输出m行,每行按yyyy-mm-dd的个数输出。
示例1
输入:
1 2008 2 3 100输出:
2008-05-13
二、代码
完整的日期类代码请参考:C++ 一个完整的日期类实现-CSDN博客
#include<iostream>
using namespace std;
class Date
{
protected:
friend ostream& operator<<(ostream& out, const Date& d);
public:
Date(int year,int month,int day);
Date operator+(int n);
int GetMonthDay(int year, int month);
private:
int _year;
int _month;
int _day;
};
Date::Date(int year,int month,int day)
{
_day=day;
_month=month;
_year=year;
}
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)
{
int year = _year;
int month = _month;
int day = _day;
int days = GetMonthDay(year, month);
while (day + n > days)
{
month++;
if (month > 12)
{
year++;
month = 1;
}
n -= days;
days = GetMonthDay(year, month);
}
day += n;
return Date(year, month, day);
}
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;
}
int main()
{
int count=0;
int year=0,month=0,day=0;
int n=0;
cin>>count;
for(int cur=0;cur<count;cur++)
{
cin>>year>>month>>day>>n;
Date d(year,month,day);
Date d1=d+n;
cout<<d1<<endl;
}
return 0;
}