gpt4 book ai didi

python - Python程序输出错误

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:39 24 4
gpt4 key购买 nike

编写代码找出列表中的最大数字

import sys

print ("Enter number of elements \n")

i = int(sys.stdin.read())

print ("Enter numbers \n")

input = sys.stdin.read()

numbers = input.split()

print ("Number of elements in list",len(numbers))

if (len(numbers)<=i):

print ("Valid Inputs \n", len(numbers))

max_index1=-1

for x in range(len(numbers)):

if ((max_index1==-1)or(numbers[x] >= numbers[max_index1])):

max_index1=x

print ("max index is",max_index1)

print ("Highest input number is", numbers[max_index1])

执行此代码时,我得到正确的输出,如下所示:

Enter number of elements

5
Enter numbers

10 45 32 23 21
Number of elements in list 5
Valid Inputs

5
max index is 0
max index is 1
Highest input number is 45

但有时输出完全错误:

Enter number of elements

5
Enter numbers

10 45 32 6 21
Number of elements in list 5
Valid Inputs
5
max index is 0
max index is 1
max index is 3
Highest input number is 6

有人可以帮我修复这个代码吗?

最佳答案

您想要做的是使用 max 函数。您可以对数字数组调用 max,它将返回最大的数字。

num_array = [5, 3, 6, 12, 3, 5]
largest = max(num_array)
print("Max num: {}".format(largest))

关于python - Python程序输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40456131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com