最高负值

Highest Negative Value

我不明白为什么这不起作用。我想打印一系列用户输入的负整数中的 最高负值 。例如,用户输入:-1、-5、-3,程序 returns -1。但是我的程序(如下)返回 -5。为什么是这样?我的代码完全搞砸了吗?我知道我可以使用列表和最大方式解决它,但我不想使程序过于复杂。

x = 0
done = False
while not done:
    y = int(input("Enter another number (0 to end): "))
    num = y
    if num != 0:
        if num < x:
            x = num
    else:
        done = True
print(str(x))

您从未将输入的值与迄今为止的最大负值进行比较。您还将初始值设置为零,这不是合适的结果值。处理这些问题的一种方法是替换你的行

if num < x
    x = num

if num < 0 and (x == 0 or x < num < 0):
  x = num

当然还有其他方法,包括将x设置为尽可能小的负数。这将简化您的比较,因为在我上面的代码中有一个检查 x 以前从未设置过。

请注意,如果根本没有输入负数,则结果为零。这可能是也可能不是你想要的。

你的运算符应该大于>,不小于<才能取最大值。初始化为 -float('inf') 确保第一个负值通过条件:

x = -float('inf')
while True:
    num = int(input("Enter another number (0 to end): "))
    if num != 0:
        if num > x:
            x = num
    else:
        break
print(x)

您可以使用 while True...break 来删除 done 变量。


I know I can use a list and max way around it but I don't want to over-complicate the program.

您可以在一行中使用 iter with your sentinel 0 to call input repeatedly, collecting an iterable of negative numbers. map(int, ...) converts the iterable items to ints while max returns 最大值:

max(map(int, iter(input, '0')))

演示:

>>> m = max(map(int, iter(input, '0')))
-3
-1
-4
-2
0
>>> m
-1

嗯,最高负值与最大值相同。

现在你的循环不变式应该是 x 迄今为止观察到的最大值 。但是您实际上存储了迄今为止观察到的 最小值 :实际上,如果新值 小于 ,则将其分配给 x

所以一个快速的解决方法是更改​​为与 > 的比较。但现在初始 最大值 将是 0。我们可以更改它,例如将初始值设置为 None,如果 xNone,则将 x 设置为输入的值。

x = None
done = False
while not done:
    y = int(input("Enter another number (0 to end): "))
    num = y
    if num != 0:
        if x is None or num > x:
            x = num
    else:
        done = True

只需使用内置 max 函数来查找最大数量

numbers = []
done = False
while not done:
    number = int(input("Enter another number (0 to end): "))
    if number < 0:
        numbers.append(number)
    else:
        done = True

print(max(numbers))