人口增长

2024-07-04 18:08:09 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是“编写一个程序,预测生物种群的大致规模。应用程序应使用文本框,允许用户输入生物的起始数量、平均每日种群增长(百分比),以及生物体将要繁殖的天数。例如,假设用户输入以下值:

起始生物数:2

平均每日增长:30%

相乘天数:10“

这是我到目前为止使用for循环的代码,我一直在思考如何执行WHILE循环,请帮助:

organismnum = int(input("Enter the starting number of organism: "))
dailyIncrease = float(input("Enter the average daily increase (in percentage): "))
daysMultiply = int(input("Enter the number of days to multiply: "))

print("Day\t\tApproximate Population\n----\t--------------------------")
for day in range(1, daysMultiply + 1):
 if day == 1:
    population = organismnum
 else:
        population *= (1 + dailyIncrease / 100)
    print(format(day, "<5d"), format(population, "12,.2f"))

Tags: ofthe用户numberforinput生物int
1条回答
网友
1楼 · 发布于 2024-07-04 18:08:09

这应该行得通-只需按您的方式格式化结果:

organismnum = int(input("Enter the starting number of organism: "))
dailyIncrease = float(input("Enter the average daily increase (in percentage): "))
daysMultiply = int(input("Enter the number of days to multiply: "))

def predict_populations(org,inc,days):
    if days==0:
        return org
    else:
        new_org=org+org*(inc/100)
        return predict_populations(new_org,inc,days-1)

result=predict_populations(organismnum,dailyIncrease,daysMultiply)
print(result)

结果可能是一个浮点数,您可以将其“四舍五入”为整数

编辑: 在跟踪所有值的情况下:

organismnum = int(input("Enter the starting number of organism: "))
dailyIncrease = float(input('''Enter the average daily increase 
                                                    (inpercentage):'''))
daysMultiply = int(input("Enter the number of days to multiply: "))

def predict_populations(org,inc,days):
    cur_res=org
    cur_day=1

    yield cur_res

    while cur_day<=days:

        cur_res+=cur_res*(inc/100)
        cur_day+=1
        yield cur_res
    

result=list(predict_populations(organismnum,dailyIncrease,daysMultiply))

#now result is a list of your population
#if you want you can transfer that into a table or dictionary

table={day:pop for day,pop in enumerate(result)}#key=day,value=population

相关问题 更多 >

    热门问题