我试图找到最小和最大的数字,但是程序的输出是不正确的。最小的是产出中最大的,最大的总是比最大的小1。我输入了2,4,6,8,这是输出:
Enter a number: 2
Enter a number: 4
Enter a number: 6
Enter a number: 8
Enter a number: done
('largest is', 7)
('smallest is', 8)这是密码:
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
try:
halo = int(num)
except:
print("invalid input")
continue
for largest in range(halo):
if largest is None:
largest = halo
elif largest > halo:
largest = halo
for smallest in range(halo):
if smallest is None:
smallest = halo
elif smallest<halo:
smallest = halo
print "largest is",largest
print "smallest is",smallest发布于 2016-06-14 09:41:30
您总是将值分配给largest和smallest,因为您在for循环中将它们用作目标:
for largest in range(halo):在上面,largest将被分配给0,然后是1,然后是2,一直到halo的最后一个数字。
接下来,您以错误的方式进行了<和>的比较;只有在halo较小的情况下才更新largest。倒转你的测试。
这里根本不需要任何循环,while True循环就是循环结构。只需直接测试halo与largest和smallest
try:
halo = int(num)
except:
print("invalid input")
continue
if largest is None or halo > largest:
largest = halo
if smallest is None or halo < smallest:
smallest = halohttps://stackoverflow.com/questions/37808206
复制相似问题