我正在尝试显示用户输入数组中的最大数字。我不允许使用内置排序功能。这是我制作的代码。在运行时,它总是返回列表中的第一个整数而不是最大的整数。
integers = []
print("Please enter a list of integers.")
print("To finish entering the integers, enter a 0 for the value.")
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
integerIn = input("Please enter an integer < 0 to finish >: ")
if integerIn == int("0"):
done = True
else:
integers.append(integerIn)
return integers
floatInput()
def largestNumber(array):
maxNum = -1
for i in array:
if i > maxNum:
maxNum = i
return maxNum
def displayArray():
print("The Maximum value is: " + str(largestNumber(integers)))
displayArray()
答案 0 :(得分:0)
此任务的正确代码:
def float_input():
integers = list()
while True:
value = int(input('Enter value (or 0 to exit): '))
if value != 0:
integers.append(value)
elif value == 0:
break
return integers
print(max(float_input()))
或者,如果您想创建自己的largestNumber
函数,请使用:
def largest_number(lst):
max_elem = lst[0]
for j in lst[1:]:
if j > max_elem:
max_elem = j
return max_elem
print(largest_number([1, 2, 5, 3, 4])) # print 5