我正在创造一个捕食者-猎物的模拟

2024-10-01 15:39:55 发布

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

这是我现在的代码

#this is the input for population and predators
popOne=float(input("Enter the predator population : "))  20

popTwo=float(input("Enter the prey population :")) 1000

#period is the amount of iterations, in my case 10
period=float(input("Enter the number of periods: ")) 10

#This is the values for the given periods
A=float(input("Enter the value .1: ")) .1
B=float(input("Enter the value .01 : ")) .01
C=float(input("Enter the value .01 : ")) .01
D=float(input("Enter the value .00002: ")) .00002

#Formluas from my book for prey population, and predator population

prey=(popTwo*(1+A-(B*popOne)))

pred=(popOne*(1-C+(D*popTwo)))

i=0
for i in range(10):
    print(prey)
    print(pred)
    i = i+1 

最后一部分是我犯错误的地方。我无法让代码打印出第一次迭代,然后继续进行第二次、第三次,依此类推。在

另外,如何使输出看起来像:

^{pr2}$

等等。在


Tags: andthe代码forinputisvaluefloat
3条回答

您需要将填充更新代码放入循环中。我还建议对初始总体也使用predprey变量。下面是一些代码:

pred = float(input("Enter the predator population : ")) # use pred and prey here
prey = float(input("Enter the prey population :"))

periods = int(input("Enter the number of periods: "))

A=float(input("Enter the value .1: ")) # these should have better prompts
B=float(input("Enter the value .01 : "))
C=float(input("Enter the value .01 : "))
D=float(input("Enter the value .00002: "))

for i in range(periods):
   # update both pred and prey at once (so no temp vars are needed)
   # also, lots of unneeded parentheses were removed
   prey, pred = prey*(1 + A - B*pred), pred*(1 - C + D*prey)

   print("After period {} there are {:.0f} predators, and {:.0f} prey"
         .format(i, pred, prey))

您的代码存在许多问题:

  1. period应作为整数读取,并且可能应该使用 来控制你的循环范围。在
  2. i已由循环设置和更新,请不要尝试初始化它或 手动更新。在
  3. pred和{}的公式需要在每个 循环的迭代,即在 打印报表。它们也应该int'
  4. 在计算predprey之后,需要更新 相应的总体值popOne和{}。在
  5. 您应该将提示从"Enter the value .1: "更改为 更具信息性和通用性的内容,如"Enter the value for coefficient A: "。在

我不是百分之百的清楚你想做什么,但我觉得给prey&pred赋值的行应该在你的循环中?在

我还认为计算prey&pred值的公式将使用prey&pred的当前值,而不是用户输入的初始值?在

相关问题 更多 >

    热门问题