You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Udacity daysBetweenDates测验答案正确性的技术验证请求

问题出在你的闰年判断逻辑里!

嘿,我一眼就发现问题所在了——你的isLeapYear函数没有遵循Gregorian日历的完整闰年规则,这直接导致1900年被错误判定为闰年,最终让天数计算多了1天。

完整的闰年规则是这样的:

  • 能被4整除,但不能被100整除 → 闰年;
  • 能被100整除,同时能被400整除 → 闰年;
  • 其他情况都是平年。

1900年是整百年,它能被100整除但不能被400整除,所以它是平年,但你的代码里只判断了"能被4整除就返回True",把1900当成了闰年,这就多算了1天,导致你的结果是36524,而正确值是36523。

修正你的闰年判断函数

把isLeapYear改成下面这样,就能正确处理所有闰年情况了:

def isLeapYear(year1):
    if year1 % 4 != 0:
        return False
    elif year1 % 100 != 0:
        return True
    else:
        return year1 % 400 == 0

同步修正其他依赖函数

为了避免重复逻辑,你的numberOfLeapYears可以直接调用修正后的isLeapYear,这样更可靠:

def numberOfLeapYears(year1, year2):
    number_of_leap_years = 0
    while year1 < year2:
        if isLeapYear(year1):
            number_of_leap_years += 1
        year1 += 1
    return number_of_leap_years

甚至numberOfNonLeapYears还能简化成这样,不用再写循环:

def numberOfNonLeapYears(year1, year2):
    total_years = year2 - year1
    return total_years - numberOfLeapYears(year1, year2)

验证结果

修正后,1900年被正确判定为平年:

  • 1900年1月1日到1999年12月31日一共包含100个年份,其中闰年有24个(1904、1908……1996),平年76个(包括1900);
  • 从1900-1-1到2000-1-1的总天数是24*366 + 76*365 = 36524天;
  • 你的daysBetweenDates计算的是到1999-12-31,比到2000-1-1少1天,正好是36523天,和Udacity的预期一致。

现在运行你的测试用例,应该就能全部通过啦!

内容的提问来源于stack exchange,提问作者Mary Grace Ona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:44:08