2016-11-27 77 views
-2
year = int(input("Enter a year: ")) 
if (year % 4) == 0: 
    if (year % 100) == 0 and (year % 400) == 0: 
     print (year, "IS a leap year.") 
else: 
    print (year, "is NOT a leap year.") 

出於某種原因,程序在輸入後不會打印任何內容。閏年計算器不打印任何輸出

下面是閏年規則鏈接,如果有人需要它:https://www.wwu.edu/skywise/leapyear.html

+0

當我運行代碼並輸入任意數字時,程序會相應地打印.... – glls

+4

第二個if語句沒有'else'條件。所以當數字可以被4整除,但不能被100或400整除時,程序將什麼也不做。 –

+0

@glls它適用於某些數字,但它不適用於其他人。所以說,2000年的輸入打印出來的東西,但2008年沒有:/ –

回答

0

好了,不打印任何東西是一樣@約翰戈登說的理由:錯過一些else子句在你的程序。我已修改爲以下代碼:

year = int(input("Enter a year: ")) 
if (year % 4) == 0: 
    if (year % 100) == 0 and (year % 400) != 0: 
     print (year, "is NOT leap year.") 
    else: 
     print (year, "is a leap year.") 
else: 
    print (year, "is NOT a leap year.") 

當一年可以除以4時,它可能是閏年。從這個意義上講,當它除以100但不能被400除時,這不是閏年。在其他情況下,它是。只需你錯過了一些情況year % 4 == 0的情況。

對於我來說,我通常在下面的代碼判斷閏年:

def is_leap_year(year): 
    if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: 
     return True 
    return False 
0

下面是我從「C程序設計語言第2版」所採取的程序:

year = int(input("Enter a year: ")) 
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: 
    print "Leap year" 
else: 
    print "Not leap" 

我認爲這些規則提供你提到的鏈接是錯誤的。一個閏年應該可以被4整除,而且必須是而不是可以被100整除。但是,如果它能被100除盡也可以被400整除,那麼就是跳躍。