You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python无列表实现输入年龄取最大两个值程序的BUG排查请求

Fixing Your Age Tracking Program

Let's break down the issues in your code and fix them step by step:

Main Problems in Your Original Code

  1. Unprocessed First Input: You read the first age, but immediately overwrite it with a new input at the start of the loop before ever checking if it should update oldest_age or second_oldest_age. That's why your input of 10 was completely ignored!
  2. Premature Printing: Your print statement is inside the else block, which means it runs every time an age doesn't fit the if or elif conditions—way too early. You only need to print once after all input is done.
  3. Missing Duplicate Handling: If you enter duplicate maximum ages (like 20, 20), your original code wouldn't update the second oldest age correctly.

Corrected Code

oldest_age = 0 
second_oldest_age = 0 

# Read the first age to start the loop
age = int(input()) 

while age != -1: 
    # Process the current age before reading the next one
    if age > oldest_age: 
        second_oldest_age = oldest_age 
        oldest_age = age 
    elif age > second_oldest_age: 
        second_oldest_age = age 
    
    # Read the next age for the next iteration
    age = int(input()) 

# Print the results once after input is complete
print(oldest_age, second_oldest_age)

How It Works with Your Test Case (10, 11, -1)

  1. First input is 10: we process it, updating oldest_age to 10 and second_oldest_age stays 0.
  2. Next input is 11: it's larger than 10, so second_oldest_age becomes 10 and oldest_age becomes 11.
  3. Final input is -1: loop exits, and we print 11 and 10—exactly what you need!

Edge Case Notes

  • If you enter duplicate maximum ages (e.g., 20, 20, -1), the code will correctly output 20 and 20.
  • If you only enter one age before -1 (e.g., 5, -1), it will output 5 and 0—you could add a check for this if you want to handle single-input cases differently, but that's beyond the original problem scope.

内容的提问来源于stack exchange,提问作者Annahita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 18:47:33