首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python程序从输入中查找两个最老的输入(没有列表)

Python程序从输入中查找两个最老的输入(没有列表)
EN

Stack Overflow用户
提问于 2022-08-30 14:31:49
回答 1查看 86关注 0票数 -1

在这个练习中,程序必须得到输入(输入是人的年龄),直到"-1“被输入.After -1”,程序必须打印两个最大的数字(两个最年长的人的年龄)。但我不允许使用名单。我想出了下面的程序,但问题是,当我只输入数字10 11,然后-1,程序输出11作为最大数字(最老),0作为第二大数字(第二大),而它应该打印11作为最大的数字和10作为第二大数字。你觉得我的代码有什么问题?

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-30 14:34:45

将输入移到循环的末尾。如果不这样做,则不会使用第一个输入(除了在while循环条件下),因为它会被下一个输入立即重写。

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73544190

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档