首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用组织增长循环Python,但没有提供适当的输出

用组织增长循环Python,但没有提供适当的输出
EN

Stack Overflow用户
提问于 2019-02-02 00:36:30
回答 3查看 7.2K关注 0票数 0

我正在编写一个程序来计算某一段时间内生长的有机体的数量:

当地的生物学家需要一个程序来预测人口增长。这些投入将是:

  • 生物的初始数量
  • 增长率(大于1的实数)
  • 达到这一比率所需的小时数
  • 人口增长的几个小时

例如,一个人可能从500个有机体的数量开始,增长率为2,以及达到6小时的增长率。假设这些生物没有死亡,这就意味着每隔6小时,这些生物的数量就会翻倍。因此,在允许6个小时的生长后,我们将有1000种生物,12小时后,我们将有2000种生物。

编写一个程序,该程序接受这些输入,并显示对总人口的预测。

下面是我到目前为止掌握的代码:

代码语言:javascript
复制
#Currently trying with 10, 2, 2, 6, giving a total pop of 10

organisms = int(input("Enter the initial number of organisms:"))
rateOfGrowth = int(input("Enter the rate of growth [a real number > 0]: "))
numOfHours = int(input("Enter the number of hours to achieve the rate of growth: "))
totalHours = int(input("Enter the total hours of growth: "))

totalOrganisms = organisms
while numOfHours >= totalHours:
    organisms *= rateOfGrowth
    totalOrganisms += organisms
    numOfHours += numOfHours
print("The total population is ",totalOrganisms)

我已经重复了几次逻辑,不明白为什么我不能得到想要的答案-- 80的

EN

回答 3

Stack Overflow用户

发布于 2019-02-02 00:52:40

您不需要一个循环,这可以用一个简单的指数增长公式来计算:

代码语言:javascript
复制
totalOrganisms = math.floor(organisms * rateOfGrowth ** (totalHours / numOfHours))

我使用math.floor(),因为如果totalHours不是numOfHours的倍数,那么公式可以产生分数,但是你不能有半个有机体。

如果您真的需要使用循环,则有两个问题。

首先,循环条件是向后的,它应该使用<=而不是>=

其次,numOfHours += numOfHours每次都会将这个变量翻一番。您需要为模拟运行的时间使用一个单独的变量。

第三,您不需要乘以organisms并将其添加到totalOrganisms中。只要把organisms乘以增长率,那将是新的有机体总数。

代码语言:javascript
复制
hoursSoFar = 0
while hoursSoFar <= totalHours:
    organisms *= rateOfGrowth
    hoursSoFar += numOfHours
print("The total population is", organisms)

但是,如果totalHours不是numOfHours的倍数,这将忽略上一段时间内的增长。

忽略部分周期的等效公式将使用整数除法:

代码语言:javascript
复制
totalOrganisms = organisms * rateOfGrowth ** (totalHours // numOfHours)
票数 0
EN

Stack Overflow用户

发布于 2020-02-06 06:28:01

代码语言:javascript
复制
organisms = int(input("Enter the initial number of organisms:"))
rateOfGrowth = int(input("Enter the rate of growth : "))
numOfhours = int(input("Enter the number of hours to achieve the rate of growth: "))
totalhours = int(input("Enter the total hours of growth: "))
hours=0
while (hours <= totalhours):
    organisms*=rateOfGrowth
    hours += numOfhours
    if (hours==totalhours):
        break
print("The total population:" ,organisms)
票数 0
EN

Stack Overflow用户

发布于 2020-10-20 15:09:15

代码语言:javascript
复制
number = int(input("Enter the initial number of organisms: "))
rate = float(input("Enter the rate of growth [a real number > 1]: "))
cycleHours = int(input("Enter the number of hours to achieve the rate of growth:"))
totalHours = int(input("Enter the total hours of growth: "))
cycles = totalHours // cycleHours
for eachPass in range(cycles):
    number = number * rate
    print("The total population is", int(number))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54488868

复制
相关文章

相似问题

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