我必须得到int的用户输入并将它们存储在一个数组中,并在列表中打印最大数字。但我必须创建自己的最大功能。我不确定将什么步骤实现到我的代码中。
def getInt(prompt):
n = int
done = False
while not done:
try:
n = int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
if n == 0:
done = True
return n
def maxNum(l):
maxi = [0]
for num in l:
if maxi > num:
maxi = num
return maxi
def result():
print("The maxium value is: " + maxNum(i))
def main():
num = []
i = 0
done = False
while not done:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
done = True
results = maxNum(i)
答案 0 :(得分:1)
以下代码完全符合您的要求。
def getInt(prompt):
try:
n = int(input(prompt))
return n
except ValueError:
print("I was expecting a number, please try again...")
getInt()
def maxNum(lst):
if not lst: # if list is empty
return None
max_elem = lst[0]
for x in lst:
if x > max_elem:
max_elem = x
return max_elem
def main():
nums = []
while True:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
break
nums.append(num)
result = maxNum(nums)
print("The maxium value is: " + str(result))
main()
答案 1 :(得分:0)
python支持内置max
函数
max([1,2,3]) # return 3
并且您的代码完全错误。
如果你想输入整数数组,getInt可能是这样的。
def getInt():
array = []
while True:
x = int(input('message'))
if x == 0: break
array.append(x)
return array
,主要代码为
array = getInt()
max_value = max(array)
print (max_value)
如果你想要自己的最大功能,可以是
def max_func(array):
max_val = array[0]
for val in array:
if val > max_val: max_val = val
return max_val
答案 2 :(得分:0)
以下是maxNum
功能的固定版本:
def maxNum(l):
if not l:
return None # or return whatever you want if user did not input anything
maxi = l[0] # it expects 'l' to be an array!
for num in l[1:]:
if maxi > num:
maxi = num
return maxi
我们还要解决您的getInt
功能:
def getInt(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
最后,您的“主要”功能需要以下修复:
def main():
num = []
n = 1
while n != 0:
n = getInt("Please enter an integer < 0 to finish >: ") # store user input into n - do not overwrite num!
num.append(n) # append each user value to the list num
results = maxNum(num) # pass the entire *list* to maxNum