Python闰年判断程序输入1992返回错误结果,求排查问题
闰年判断代码错误排查与修复
问题定位
你的代码在处理能被4整除但不能被100整除的年份时存在逻辑错误:当year % 4 == 0且year % 100 != 0时,错误地将leap赋值为False,而根据闰年规则,这类年份本身就是闰年,应设为True。
闰年规则回顾
- 能被400整除 → 闰年
- 能被100整除但不能被400整除 → 非闰年
- 能被4整除但不能被100整除 → 闰年
- 其他情况 → 非闰年
修复后的代码
def is_leap(year): leap = False if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: leap = True else: leap = False else: # 能被4整除但不能被100整除,判定为闰年 leap = True else: leap = False return leap year = int(input()) print(is_leap(year))
验证结果
输入1992时,1992 %4 ==0且1992%100 !=0,修复后的代码会将leap设为True,符合实际闰年判定。
内容的提问来源于stack exchange,提问作者Black Operative
相关产品推荐
相关产品推荐

