编译器:C++ (g++)
改造练习13-1(日复一日)中的Date类并提交,使其可以与一个整数n相加或相减,得到该日期N天后/前的日期。
提示:
-
请参考题目(日复一日)中的Date类实现;
-
注意考虑闰月;
-
整数n的取值范围为[1,10000]。
裁判测试程序样例:
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
//在此处补充Date类的定义
int main()
{
int y, m, d;
cin >> y >> m >> d;
Date d1(y,m,d);
int n;
cin >> n;
cout << d1.toText() << " + " << n << " = " << (d1 + n).toText() << endl;
cout << d1.toText() << " - " << n << " = " << (d1 - n).toText() << endl;
return 0;
}
输入样例:
2022 8 31
2
说明:意为求2022年8月31日的后两天和前两天的日期。
输出样例:
2022-8-31 + 2 = 2022-9-2
2022-8-31 - 2 = 2022-8-29
请注意:函数题只需要提交相关代码片段,不要提交完整程序。
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
//在此处补充Date类的定义
class Date {
public:
Date(int year, int month, int day) : year_(year), month_(month), day_(day) {}
int getYear() const { return year_; }
int getMonth() const { return month_; }
int getDay() const { return day_; }
string toText() const {
string str = to_string(year_) + "-" + to_string(month_) + "-" + to_string(day_);
return str;
}
Date operator+(int n) const {
int daysInMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int days = day_ + n;
int month = month_;
int year = year_;
while (days > daysInMonth[month - 1]) {
if (month == 2 && isLeapYear()) {
if (days > 29) {
days -= 29;
month++;
} else {
break;
}
} else {
days -= daysInMonth[month - 1];
month++;
}
if (month > 12) {
year++;
month = 1;
}
}
return Date(year, month, days);
}
Date operator-(int n) const {
int days = day_ - n;
int month = month_;
int year = year_;
while (days <= 0) {
if (month == 3 && isLeapYear()) {
days += 29;
month--;
} else {
month--;
if (month == 0) {
year--;
month = 12;
}
days += daysInMonth(month - 1);
}
}
return Date(year, month, days);
}
private:
int year_, month_, day_;
bool isLeapYear() const {
if (year_ % 4 == 0 && year_ % 100 != 0 || year_ % 400 == 0) {
return true;
} else {
return false;
}
}
int daysInMonth(int month) const {
if (month == 1 && isLeapYear()) {
return 29;
} else {
return daysInMonth_[month];
}
}
static const int daysInMonth_[12];
};
const int Date::daysInMonth_[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
int main()
{
int y, m, d;
cin >> y >> m >> d;
Date d1(y,m,d);
int n;
cin >> n;
cout << d1.toText() << " + " << n << " = " << (d1 + n).toText() << endl;
cout << d1.toText() << " - " << n << " = " << (d1 - n).toText() << endl;
return 0;
}