我有一个程序使用我在一个类中定义的两个函数。我的类(class)工作正常,但我的程序总是返回一定数量的假期。当日期相距较远时,会出现更多错误。我的代码旨在在一个函数中计算自 1582 年以来的总天数,另一个函数从较小的天数中减去较高的天数。我从哪里得到错误?我知道这可能不是最有效的做事方式(cpu 明智的)但是有人能找到我的逻辑在哪里搞砸了吗?这也说明了闰年。我一直在根据网站检查我的程序 http://www.timeanddate.com/date/durationresult.html
int Date::totalDays()
{
int totalDays = 0;
int daysInMonth[]={0,31,28,31,30,31,30,31,31,31,31,30,31};
totalDays += day;
for (int i = month-1; i > 0; i--)
{
totalDays += daysInMonth[i];
}
for (int i = year-1; i > 1582; i--)
{
if(year % 100 == 0)
{
if(year % 400 == 0)
totalDays += 366;
else
totalDays += 365;
}
else
{
if(year % 4 == 0)
totalDays += 366;
else
totalDays += 365;
}
}
return totalDays;
}
int Date::daysBetween(Date other)
{
if (this->totalDays() > other.totalDays())
return this->totalDays() - other.totalDays();
else
return other.totalDays() - this->totalDays();
}
谢谢。
最佳答案
问题一:
int daysInMonth[]={0,31,28,31,30,31,30,31,31,31,31,30,31};
应该是
int daysInMonth[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
// ^^
问题2:
如果当前 year
是闰年,并且 month
大于 2,您还需要添加一天来计算 2 月 29 日当前年份。
关于c++ - 两个日期之间有多少天 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36045961/