[英]Question is Find the 2nd largest digit ,What is wrong with my code, I am a beginner
問題是求第2大的數字,我的代碼有什么問題,我是初學者,Output還是0
a = input("Enter your number")
max = 0
maxx = 0
list1 = []
for i in a :
list1.append(i)
if i > str(max) :
max = i
list1.remove(max)
for j in list1 :
if j > str(maxx) :
maxx = j
print(maxx)
第二個for
循環不應該嵌套在這樣的條件語句中,因為它只會運行到找到最大數字為止。
另一個主要問題是,即使沒有嵌套第二個for
循環,在a = '12345'
的情況下,每個數字都是第一個循環找到的最高數字,因此從list1
中刪除,這意味着list1
最終完全為空。
這應該有效:
a = input("Enter your number: ")
max_num = 0
maxx = 0
for i in a :
if i > str(max_num) :
max_num = i
for j in a :
if j > str(maxx) and j < str(max_num):
maxx = j
print(maxx)
或者你也可以這樣做:
nums = input('Enter numbers: ')
list1 = []
for i in nums:
list1.append(int(i))
list1.sort()
print(list1[-2])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.