1.题目:
2.分析:
见代码。
3.我的代码:
#include <iostream>
using namespace std;
class Date
{
public:
Date(int year = 1)
: _year(year) {}
inline int GetMonthDay(int year, int month)
{
static int arr[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if ((month == 2) && ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))))
{
return 29;
}
else
{
return arr[month];
}
}
void ShowDate(int addDay)
{
_day = addDay;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
++_month;
if (_month > 12)
{
_month -= 12;
++_year;
}
}
if (_month < 10 && _day < 10)
{
cout << _year << "-0" << _month << "-0" << _day << endl;
}
else if (_month < 10 && _day >= 10)
{
cout << _year << "-0" << _month << "-" << _day << endl;
}
else if (_month >= 10 && _day < 10)
{
cout << _year << "-" << _month << "-0" << _day << endl;
}
else
{
cout << _year << "-" << _month << "-" << _day << endl;
}
}
private:
int _year = 1;
int _month = 1;
int _day = 1;
};
int main()
{
int year = 0;
int addDay = 0;
cin >> year >> addDay;
Date date(year);
date.ShowDate(addDay);
}
4.答案代码:
#include <iostream>
using namespace std;
int main()
{
int year;
int day;
int mon[13] = {31, 28, 31, 30, 31, 30, 31, 31, 30 ,31, 30, 31};
while(cin>>year>>day)
{
if(((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
mon[1] = 29;
else
mon[1] = 28;
for(int i = 0; i < 12; i++)
{
if(day <= mon[i])
{
printf("%04d-%02d-%02d\n", year, i + 1, day);
break;
}
else
{
day = day - mon[i];
}
}
}
return 0;
}