在这个练习中,程序必须得到输入(输入是人的年龄),直到"-1“被输入.After -1”,程序必须打印两个最大的数字(两个最年长的人的年龄)。但我不允许使用名单。我想出了下面的程序,但问题是,当我只输入数字10 11,然后-1,程序输出11作为最大数字(最老),0作为第二大数字(第二大),而它应该打印11作为最大的数字和10作为第二大数字。你觉得我的代码有什么问题?
oldest_age=0
second_oldest_age=0
age=int(input())
while age!=-1:
age=int(input())
if age>oldest_age:
second_oldest_age=oldest_age
oldest_age=age
elif age<oldest_age and age>second_oldest_age:
second_oldest_age=age
else:
print(oldest_age, second_oldest_age)发布于 2022-08-30 14:34:45
将输入移到循环的末尾。如果不这样做,则不会使用第一个输入(除了在while循环条件下),因为它会被下一个输入立即重写。
oldest_age = 0
second_oldest_age = 0
age = int(input())
while age != -1:
if age > oldest_age:
second_oldest_age = oldest_age
oldest_age = age
elif age > second_oldest_age: # 'age < oldest_age' is not needed here
second_oldest_age = age
age = int(input()) # Moved this from the start to the end
else:
print(oldest_age, second_oldest_age)https://stackoverflow.com/questions/73544190
复制相似问题