我正在编写一个程序来计算某一段时间内生长的有机体的数量:
当地的生物学家需要一个程序来预测人口增长。这些投入将是:
例如,一个人可能从500个有机体的数量开始,增长率为2,以及达到6小时的增长率。假设这些生物没有死亡,这就意味着每隔6小时,这些生物的数量就会翻倍。因此,在允许6个小时的生长后,我们将有1000种生物,12小时后,我们将有2000种生物。
编写一个程序,该程序接受这些输入,并显示对总人口的预测。
下面是我到目前为止掌握的代码:
#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的
发布于 2019-02-02 00:52:40
您不需要一个循环,这可以用一个简单的指数增长公式来计算:
totalOrganisms = math.floor(organisms * rateOfGrowth ** (totalHours / numOfHours))我使用math.floor(),因为如果totalHours不是numOfHours的倍数,那么公式可以产生分数,但是你不能有半个有机体。
如果您真的需要使用循环,则有两个问题。
首先,循环条件是向后的,它应该使用<=而不是>=。
其次,numOfHours += numOfHours每次都会将这个变量翻一番。您需要为模拟运行的时间使用一个单独的变量。
第三,您不需要乘以organisms并将其添加到totalOrganisms中。只要把organisms乘以增长率,那将是新的有机体总数。
hoursSoFar = 0
while hoursSoFar <= totalHours:
organisms *= rateOfGrowth
hoursSoFar += numOfHours
print("The total population is", organisms)但是,如果totalHours不是numOfHours的倍数,这将忽略上一段时间内的增长。
忽略部分周期的等效公式将使用整数除法:
totalOrganisms = organisms * rateOfGrowth ** (totalHours // numOfHours)发布于 2020-02-06 06:28:01
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)发布于 2020-10-20 15:09:15
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))https://stackoverflow.com/questions/54488868
复制相似问题