这个程序解决的问题
1.最近手中有一些资金,按照我现在余额,我算出了我还能定投x天,但是因为周末放假是不能进行定投的,只有周内可以。所以即使我知道了我现在能定投多少天,但也不能解决我想知道以我现在的资金,我可以最多坚持到定投到某一年的某个日子,于是乎,我灵机一动,最近正好在学c++,所以就有了下面这个程序。
程序解读
1.在想到要靠程序来解决问题的时候,我第一个就想到了闰年,闰月的问题,于是乎,我决定创建一个日期类,和一个周类,因为,周和日期之间没有特别的相关联条件,所以每过一天,就要给这个个周加一天,到了周末则置1;
2.week类中我重载了++运算符,为了方便周的++,每次只需要调用++,week类就会自动处理周的循环
3.在Date类中,有个主要的函数,就是判断这个月有多少天,其实也就涉及到了年月日的进位问题。类中有详细的注释,不再赘述。
实现
class weekday {
public:
weekday(int week){//构造函数
if (week <= 7 && week >= 1) {
_week = week;
}
else {
assert(0);
}
};
int getIsWeek() {//返回周几
return _week;
}
public://重载----------------------------------------
weekday& operator++() {
if (_week < 7) {
_week++;
}
else {
_week = 1;
}
return *this;
}
private:
int _week;
};
class Date {
public:
Date(int year = 2019, int month = 11, int day = 6,int week = 3)
:_year(year)
,_month(month)
,_day(day)
,_weekday(week)
{}
public://功能---------------------------------
int getDayIsWeek() {
return _weekday.getIsWeek();
}
public://重载-------------------------------
friend ostream& operator<<(ostream& out, Date& d);//<<重载
int& operator++() {
int monDay = getDaysOfMonth(_year,_month);
if (_day < monDay) {//不是本月最后一天
_day++;
}
else if (_month < 12) {//是本月最后一天且,month不是12月
_month++;
_day=1;
}
else {//是本月最后一天且,month==12
_month = 1;
_day = 1;
_year++;
}
++_weekday;
return _day;
}
private://内部函数-----------------------------------
int getDaysOfMonth(int year, int month) {
if (month > 12 || month < 0) {
assert(1);
}
int DaysOfMonth[12] = { 31,28,31,30,
31,30,31,31,
30,31,30,31 };
if ( month == 2 && getIsLeap(year)) {
DaysOfMonth[1]++;
}
return DaysOfMonth[month - 1];
}
int getIsLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
private:
int _year;
int _month;
int _day;
weekday _weekday;
};
ostream& operator<<(ostream& out, Date& d) {
cout << d._year << ":" << d._month << ":" << d._day << endl;
return out;
}
Date PrintTheWeekDayAfterDays(int n) {
int count = 0;
Date d;
for (int i = n;i > 0;) {
if (d.getDayIsWeek() <= 5 && d.getDayIsWeek() >= 1) {
i--;
}
++d;
}
return d;
}
int main() {
Date d = PrintTheWeekDayAfterDays(154);
cout << d;
system("pause");
}