我正在運行一個代碼,它必須列印用戶輸入的 5 個中最高的數字。如果我在前三個輸入中輸入最大的數字,它就可以正常作業并列印出最大的數字。但如果我在輸入 4 或 5 中輸入最高數字,它不會列印任何內容。
我已經看了一個小時,試圖找出問題所在,但找不到任何東西。
a = int(input("ENTER NUMBER 1:"))
b = int(input("ENTER NUMBER 2:"))
c = int(input("ENTER NUMBER 3:"))
d = int(input("ENTER NUMBER 4:"))
e = int(input("ENTER NUMBER 5:"))
if a > b:
if a > c:
if a > d:
if a > e:
print("Number 1 is the greatest")
elif b > c:
if b > d:
if b > e:
print("Number 2 is the greatest")
elif c > d:
if c > a:
if c > e:
print("Number 3 is the greatest")
elif d > a:
if d > b:
if d > e:
print("Number 4 is the greatest")
elif e > a:
if e > b:
if e > c:
print("Number 5 is the greatest")
uj5u.com熱心網友回復:
如果內部條件變為假,那么代碼只會停在那里。
嘗試else為內部if條件設定條件以了解代碼哪里出錯了。
最好避免太多條件(建議)。
如果您知道邏輯運算子,請參閱下面的代碼。
a = int(input("ENTER NUMBER 1:"))
b = int(input("ENTER NUMBER 2:"))
c = int(input("ENTER NUMBER 3:"))
d = int(input("ENTER NUMBER 4:"))
e = int(input("ENTER NUMBER 5:"))
if (a > b and a > c and a > d and a > e):
print("Number 1 is the greatest")
elif (b > c and b > d and b > e):
print("Number 2 is the greatest")
elif (c > d and c > a and c > e):
print("Number 3 is the greatest")
elif (d > a and d > b and d > e):
print("Number 4 is the greatest")
elif (e > a and e > b and e > c):
print("Number 5 is the greatest")
else:
print('else case')
uj5u.com熱心網友回復:
我假設這是 Python,但如果我錯了,這個答案應該仍然普遍適用。
查看前幾行并考慮輸入 a=5, b=1, c=10, d=1, e=1。
if a > b:
if a > c:
if a > d:
if a > e:
print("Number 1 is the greatest")
elif b > c:
第一次檢查 (a > b) 為真 (5 > 1),因此它將進入代碼的該部分(并且永遠不會到達其他elifs)。下一次檢查 (a > c) 不成立,因此它將在到達print陳述句之前停止。
要完成您嘗試做的基本想法,您需要更多類似的東西:
if a > b and a > c and a > d and a > e:
print("Number 1 is the greatest")
elif b > c and b > d and b > e:
print("Number 2 is the greatest")
elif c > d and c > a and c > e:
print("Number 3 is the greatest")
elif d > a and d > b and d > e:
print("Number 4 is the greatest")
elif e > a and e > b and e > c:
print("Number 5 is the greatest")
但是,即使這樣也可能是不正確的,因為要處理關系,您需要else在末尾而不是elifwith 條件。(如果所有變數都相同,則沒有一個>條件為真)。
正如評論所建議的那樣,回圈遍歷并記住最高值的位置可能會更好。或者可能對串列進行排序。如果您需要擴展它,這樣的事情會更好(例如,如果您想要 100 個輸入而不是 5 個,回圈遍歷一個陣列將幾乎相同,但您不想撰寫數百個條件)。
也許像下面這樣的東西會更易于維護和除錯(您可以更改ni以設定要讀取和檢查的元素數量)。
ni = 5
a = []
for i in range(0, ni):
ele = int(input())
a.append(ele)
b = None
for i in range(0, ni):
if b == None or b < a[i]:
b = a[i]
c = i
print("Number " str(c 1) " is the greatest")
編輯添加:如果您對這些值所做的只是檢查最大值,那么您甚至根本不需要存盤它們。你可以在他們進來時檢查他們。
ni = 5
b = None
for i in range(0, ni):
ele = int(input())
if b == None or b < ele:
b = ele
c = i
print("Number " str(c 1) " is the greatest")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416349.html
標籤:
