编译器: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 请注意:函数题只需要提交相关代码片段,不要提交完整程序。
时间: 2024-01-11 17:02:58 浏览: 98
C++实现日期类(Date)
5星 · 资源好评率100%
```cpp
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
class Date {
private:
int year, month, day;
static const int monthDays[13];
public:
Date(int y = 1, int m = 1, int d = 1) {
year = y;
month = m;
day = d;
}
Date(const Date& date) {
year = date.year;
month = date.month;
day = date.day;
}
Date& operator=(const Date& date) {
year = date.year;
month = date.month;
day = date.day;
return *this;
}
bool isLeap() const {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int monthDaysNum() const {
if (month == 2 && isLeap()) {
return 29;
}
return monthDays[month];
}
void addOneDay() {
day++;
if (day > monthDaysNum()) {
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
}
}
}
void minusOneDay() {
day--;
if (day == 0) {
month--;
if (month == 0) {
month = 12;
year--;
}
day = monthDaysNum();
}
}
string toText() const {
string res = "";
res += to_string(year) + "-";
if (month < 10) {
res += "0";
}
res += to_string(month) + "-";
if (day < 10) {
res += "0";
}
res += to_string(day);
return res;
}
Date operator+(int n) const {
Date res = *this;
while (n--) {
res.addOneDay();
}
return res;
}
Date operator-(int n) const {
Date res = *this;
while (n--) {
res.minusOneDay();
}
return res;
}
};
const int Date::monthDays[13] = {0,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;
}
```
阅读全文