如何在不使用最小和最大函数的情况下获得最小和最大?

时间:2020-03-31 13:10:05

标签: python

我试图在不使用min和max函数的情况下找到最大值和最小值。但是最大值仅显示第一个数字。有帮助吗?

我的代码:

count = 0
total = 0.0

num = float(input("Enter the number: ")) 
maximum = num
minimum = num

while num = 0:
    count = count + 1
    total = total + num
    num = float(input("Enter the number: "))

if num < minimum:
    minimum = num
else:
    num > maximum
    maximum = num

if count == 0:
    print("Invalid Entry.")
else:
    print("Average Number:", round(total/count, 1))
    print("Minimum Number:", minimum)
    print("Maximum Number:", maximum)

4 个答案:

答案 0 :(得分:1)

您并不想使用if条件,这就是为什么它不起作用的原因
我已经修改了一次尝试一次获得6个数字的代码

count = 0
total = 0.0

num = float(input("Enter the number: ")) 
maximum = num
minimum = num

while count < 5:
    count = count + 1
    total = total + num
    num = float(input("Enter the number: "))

    if num < minimum:
       minimum = num
    else:
       num > maximum
       maximum = num

if count == 0:
    print("Invalid Entry.")
else:
    print("Average Number:", round(total/count, 1))
    print("Minimum Number:", minimum)
    print("Maximum Number:", maximum)

答案 1 :(得分:0)

count = 0
total = 0.0

num = None 
maximum = -float("inf")
minimum = float("inf")
# No need to do the 1st round outside the loop
while num != 0:
    num = float(input("Enter the number: "))
    count += 1
    total += num  # += is more concise

    # This block needs to be in the while loop
    if num < minimum:
        minimum = num
    if num > maximum:  # elif is fine if you initialize minimum and maximumwith the 1st value of num
        maximum = num

if count == 0:
    print("Invalid Entry.")
else:
    print("Average Number:", round(total/count, 1))
    print("Minimum Number:", minimum)
    print("Maximum Number:", maximum)

答案 2 :(得分:0)

我不太确定您要在这里完成什么。如果您的第一个输入不是0,则将变量maximum和minimum设置为该非零数字。您将跳过while循环和if语句。如果没有错误,它可能只会吐出最大和最小相同的数字。您可以提供有关您要做什么的更多详细信息吗?

答案 3 :(得分:0)

您需要检查每个数字的最小值和最大值。所以这部分必须在while循环中:

if num < minimum:
  minimum = num

if num > maximum
  maximum = num

虽然条件似乎不正确。您每次都会为num分配0。您可能是指num!= 0。在这种情况下,当用户输入0时,程序将终止。