我应该如何处理这段代码来检查 1900 年之后的闰年?

问题描述 投票:0回答:3
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 年的错误结果。

我该怎么办?

python python-3.x leap-year
3个回答
1
投票

条件

( year % 400 == 0 and year % 100 == 0 ) or ( year % 4 ==0 )

是错误的。更改您的代码,以便

  1. year % 400 == 0
    闰年
  2. year % 100 == 0
    不是闰年
  3. year % 4 == 0
    闰年
  4. 所有其他:不是闰年

您也可以使用此算法:https://en.wikipedia.org/wiki/Leap_year#Algorithm


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(年))


0
投票

这是因为您的条件 (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))
© www.soinside.com 2019 - 2024. All rights reserved.