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

Python人口增长计算程序故障:无法完成多代迭代计算

人口增长计算程序问题修复

问题根源

你的代码只能计算第一代人口的核心原因有两个:

  • 循环计算每代人口时,始终使用初始的currentPopulation值,没有将每代计算后的人口更新为下一轮的当前人口,导致所有世代都基于初始值重复计算,最终只得到第一代的结果。
  • for循环的迭代变量用了newPopulation,和你计算人口的变量重名,不仅逻辑混乱,也没有利用迭代变量的作用。

修复后的代码

while True:
    currentPopulation = int(input("\nWhat is the current population? "))
    generations = int(input("\nHow many generations do you want to wait? "))
    
    # 保存初始人口用于最终输出
    initial_pop = currentPopulation
    # 修改迭代变量名,避免和计算变量冲突
    for _gen in range(generations):
        # 先计算出生后的人口(增加10%)
        births = currentPopulation + round(currentPopulation * 0.1)
        # 再计算死亡后的人口(减少2%)
        currentPopulation = births - round(births * 0.02)
    
    print(f"\nIf population is {initial_pop} and you wait {generations} generation(s), there will be {currentPopulation} of them.")

    again = input("\nDo you want to calculate another population? (y/n) ")
    if again.lower() == "n":
        break
    elif again.lower() != "y":
        print("\nCalculating again...")
  
print("\nBye")

关键改动说明

  1. 新增initial_pop保存初始人口,确保最终输出显示的是用户输入的初始值。
  2. 将for循环的迭代变量改为_gen,避免变量名冲突,循环次数直接用generations即可(无需range(1, generations+1))。
  3. 每代计算完成后,将结果赋值给currentPopulation,让下一轮循环基于更新后的人口数计算。
  4. 简化了输入判断的逻辑,去掉了无意义的currentPopulation语句。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:30:48