def is_leap(year):
leap = False
if(( year % 400 == 0 and year % 100 == 0 ) or ( year % 4 ==0 )):
leap = True
# Write your logc here
return leap
year = int(input())
print(is_leap(year))
我使用此代码在 HackerRank python“编写函数”练习中查找 1900 年之后的闰年,但它显示 2100 年的错误结果。
我该怎么办?
条件
( year % 400 == 0 and year % 100 == 0 ) or ( year % 4 ==0 )
是错误的。更改您的代码,以便
year % 400 == 0
闰年year % 100 == 0
不是闰年year % 4 == 0
闰年def is_leap(年): 飞跃=假
if year % 400 == 0:
leap = True
elif year % 100 == 0:
leap = False
elif year % 4 == 0:
leap = True
return leap
年 = int(输入()) 打印(is_leap(年))
这是因为您的条件 (year % 4 == 0) 在 2100 年的计算结果为 True,它不能被 400 整除,但可以被 100 和 4 整除。
条件应该是 (年份 % 4 == 0 且年份 % 100 != 0)或(年份 % 400 == 0)
def is_leap(year):
leap = False
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
leap = True
return leap
year = int(input())
print(is_leap(year))