Skip to main content
 首页 » 编程设计

python之最高负值

2025年05月04日9sharpest

我不明白为什么这不起作用。我想打印一系列用户输入的负整数中的最高负值。例如,用户输入:-1、-5、-3,程序返回 -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)) 

请您参考如下方法:

您的运算符应大于 > , 不少于 <以便取最大值。初始化为 -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) 

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


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

您可以使用 iter 在一行中完成此操作 与你的哨兵 0调用input反复收集负数的 iterable。 map(int, ...) 将可迭代项转换为整数,同时 max 返回最大值:

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

演示:

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