Skip to content

Commit

Permalink
Update ex14_24.cpp
Browse files Browse the repository at this point in the history
I think the first year should be 1 year, not 0 year.Because we don't know the 0 year is or not a leap year.Even though we assume that the 0 year is a leap year,the original code has an error output of Date d1(365) and Date d2(366).What's more,when calculating some days after a date, the result is not correct due to this error.For example, 150 days after 2016/8/4 is 2017/1/1, While the result is 2017/1/2. At last, I have a question why the output of 'cout<<Date d()' is 1 not the default 1/1/1?
  • Loading branch information
windy9169 authored Aug 4, 2016
1 parent 53e1dfe commit e3077f8
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions ch14/ex14_24.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@ Date::Date(Size days)
Size y4 = (days - y400 * YtoD_400 - y100 * YtoD_100) / YtoD_4;
Size y = (days - y400 * YtoD_400 - y100 * YtoD_100 - y4 * YtoD_4) / 365;
Size d = days - y400 * YtoD_400 - y100 * YtoD_100 - y4 * YtoD_4 - y * 365;
this->year = y400 * 400 + y100 * 100 + y4 * 4 + y;
if(d==0){
this->year = y400 * 400 + y100 * 100 + y4 * 4 + y;
this->month = 12;
this->day = 31;
}
else {
this->year = y400 * 400 + y100 * 100 + y4 * 4 + y + 1;

//! check if leap and choose the months vector accordingly
std::vector<Size> currYear =
Expand All @@ -38,6 +44,7 @@ Date::Date(Size days)
else
return false;
});
}
}

//! construcotr taking iostream
Expand Down Expand Up @@ -106,12 +113,14 @@ Date::Size Date::toDays() const
for (auto it = currYear.cbegin(); it != currYear.cbegin() + this->month - 1;
++it)
result += *it;

auto pre_year = this->year - 1;

//! calculate result + days by years
result += (this->year / 400) * YtoD_400;
result += (this->year % 400 / 100) * YtoD_100;
result += (this->year % 100 / 4) * YtoD_4;
result += (this->year % 4) * YtoD_1;
result += (pre_year / 400) * YtoD_400;
result += (pre_year % 400 / 100) * YtoD_100;
result += (pre_year % 100 / 4) * YtoD_4;
result += (pre_year % 4) * YtoD_1;

return result;
}
Expand Down

0 comments on commit e3077f8

Please sign in to comment.