gpt4 book ai didi

python - 函数返回无 - 尝试在不使用 x 的情况下找到集合中的最高数字

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

嘿,所以我才刚刚开始使用 python。我正在尝试使用带返回的函数在 4 个数字中找到最大的数字。无论出于何种原因,该函数只返回值 d 并且仅当它是最高 int 时。我输入的其他一组数字没有产生。我最初使用 max 解决了它,但我不能使用 max 进行分配。请让我知道我做错了什么!!谢谢!

a=num1=int(input("Enter 1st number "))
b=num2=int(input("Enter 2nd number "))
c=num3=int(input("Enter 3rd number "))
d=num4=int(input("Enter 4th number "))


def CompareNumbers(a, b , c, d):
if(b > a):
largest=b
return largest
if(c > b):
largest= c
return largest
if(d > c):
largest= d
return largest

largest = a

e= CompareNumbers(a, b, c, d)

print(e)

最佳答案

你可能没遇到过for-loops但是,但是你会的。我的建议是在这里尝试使用一个:

def compare_numbers(a, b, c, d):
# To start out, we'll assume the
# first number is the largest, but
# we'll be double checking that.
largest = a

# We put the rest of the numbers in
# a list that we'll iterate over in
# the for-loop below
my_list = [b, c, d]

for number in my_list:
# see explanation below...

return largest

在我上面写的空 for 循环中,您需要编写一些代码来检查 largest 是否实际上大于 number。如果是,太好了!你不需要做任何事情。但如果number 是两者中较大的一个,则需要设置largest = number。如果你这样做正确,当 for 循环结束时,largest 将是你输入的四个数字中最大的一个。

关于python - 函数返回无 - 尝试在不使用 x 的情况下找到集合中的最高数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37476392/

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