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

闰年判断函数代码异常:单个测试用例未通过,请求技术排查

闰年判断代码问题排查与修正

你的代码逻辑存在顺序错误和规则遗漏,导致整百年的闰年判断出错,比如1900年这类能被4整除但不能被400整除的整百年,会被错误判定为闰年。具体问题点:

  • 第一个条件if year%4==0: return True直接返回True,忽略了整百年需要额外检查能否被400整除的规则
  • 检查year%400==0的条件放在了year%4==0之后,永远不会被执行(因为能被400整除的年份必然能被4整除,会被第一个条件拦截)
  • 后续的elif year%100 !=0逻辑混乱,无法正确过滤非闰年的整百年

正确的闰年判断逻辑应该遵循:

  • 能被400整除的年份是闰年
  • 能被100整除但不能被400整除的不是闰年
  • 能被4整除但不能被100整除的是闰年
  • 其余情况都不是闰年

修正后的代码:

def is_leap(year):
    leap = False
    if year % 400 == 0:
        leap = True
    elif year % 100 == 0:
        leap = False
    elif year % 4 == 0:
        leap = True
    return leap

year = int(input())
print(is_leap(year))

或者更简洁的写法:

def is_leap(year):
    return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)

year = int(input())
print(is_leap(year))

内容的提问来源于stack exchange,提问作者Akshita Tiwari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 06:00:47