首页 > 解决方案 > 如何修复我在这个程序中得到的 0 输出?

问题描述

我可能使这个程序比它需要的更复杂。但由于它是学习课程的一部分,我不得不在限制条件下这样做。在大多数情况下,这似乎可行,尽管我似乎总是得到一个带有“最大”整数的 0 输出。有时当输入类似的数字序列时,比如 555,我也会看到 5,0,0 返回。

我只是想要安排一系列数字的程序拉动。我确信这可以通过多种方式实现,但我想看看我拥有的这种方式是否可优化。非常感谢您的意见!

first = int(input("Enter the first number: "))
second = int(input("Enter the second number: "))
third = int(input("Enter the third number: ")) 
small = 0
middle = 0
large = 0 
if first < third and first < second:
    small = first
elif second < third and second < first:
    small = second
else:
    small = third 
if first < second and first < third:
    middle = first
    if second > first and second < third:
        middle = second
    else:
        middle = third 
elif first > second and first > third:
    large = first
    if second > first and second > third:
        large = second
    else:
        large = third
print("The numbers in accending order are: ", small, middle, large)

标签: python

解决方案


问题是if实际上并没有执行任何语句,因此small, middle, large值不会改变(它们保持初始值,0)。

这样做的原因是,当它们实际上是 EQUAL(返回False)时,您正在检查这些值是比彼此大还是小。并且由于不执行任何if语句,因此只执行else语句(因此5in 5,0,0)。

尝试做这样的事情:

# NOTE: the change is the <= and >= rather than simply < or >
if first <= third and first <= second:
    small = first
elif second <= third and second <= first:
    small = second
else:
    small = third

# NOTE: I also made a few changes to the code below

# Reason: Earlier middle wasn't being set at all if first >= second and first <= third was
# false, a similar reason goes for the large value not changing

# I also changed the definition of middle to include the fact that first can be more than
# second and less than third or vice versa (more than third and less than second)
if (first >= second and first <= third) or (first <= second and first >= third):
    middle = first
elif (second >= first and second <= third) or (second <= first and second >= third):
    middle = second
else:
    middle = third 
if first >= second and first >= third:
    large = first
elif second >= first and second >= third:
    large = second
else:
    large = third

希望这有帮助:D


推荐阅读