我們知道這是一個閏年,如果它是被4整除,如果它是一個世紀以來,它被400整除我以爲我會需要兩個if語句是這樣的:確定閏年
def isLeap(n):
if n % 100 == 0 and n % 400 == 0:
return True
if n % 4 == 0:
return True
else:
return False
# Below is a set of tests so you can check if the code is correct.
from test import testEqual
testEqual(isLeap(1944), True)
testEqual(isLeap(2011), False)
testEqual(isLeap(1986), False)
testEqual(isLeap(1956), True)
testEqual(isLeap(1957), False)
testEqual(isLeap(1800), False)
testEqual(isLeap(1900), False)
testEqual(isLeap(1600), True)
testEqual(isLeap(2056), True)
當我嘗試上面的代碼,我得到的錯誤消息年
1800 - Test Failed: expected False but got True
1900 - Test Failed: expected False but got True
基本上我需要我的代碼說,「如果今年四整除的測試結果是真,並且,如果它是一個世紀以來,它的整除400.」但是,當我嘗試:
if n % 4 and (n % 100 == 0 and n % 400 == 0):
return True
else:
return False
我得到三個錯誤消息(幾年)
1944 - Test Failed: expected True but got False
1956 - Test Failed: expected True but got False
2056 - Test Failed: expected True but got False
因此,它看起來像我創造了第二個條件(由100和400整除)已經取消了年通過4
你應該比較'如果n%4'的東西? –
'n%100 == 0和n%400 == 0'是多餘的;如果它可以被400整除,它總會被100整除。想想你的數學有點難。 –
順便說一句,[已經回答](https://stackoverflow.com/questions/11621740/how-to-determine-whether-a-year-is-a-leap-year-in-python?rq=1) –