如何在Python中使用带有for循环范围的累加器?

时间:2017-02-20 08:40:52

标签: python accumulator

我试图在Python中使用累加器,但我无法让它工作。我希望人口从2开始并增加%Increase输入,但它没有正确输出。我究竟做错了什么?我知道这是我积累的方式,但我尝试的每一次尝试都失败了。

#Get the starting number of organisms
startingNum = int(input('Enter the starting number of organisms:'))

#Get the average daily increase
percentIncrease = float(input('Enter the percentage of average daily increase of organisms:'))

#Get the number of days to multiply
number_of_Days = int(input('Enter the number of days to multiply:'))

population = 0
cumPopulation = 0

for number_of_Days in range(1,number_of_Days + 1):
    population = startingNum
    cumPopulation += population *(1+percentIncrease)
    print(number_of_Days,'\t',cumPopulation)


#So inputs of 2, .3, and 10 should become:
1   2
2   2.6
3   3.38
4   4.394
5   5.7122
6   7.42586
7   9.653619
8   12.5497
9   16.31462
10  21.209

2 个答案:

答案 0 :(得分:3)

您不确定是否需要将第1天打印为startingNum或将第1天打印为startingNum * (1+ percentIncrease)

这就是你想要的:

#Get the starting number of organisms
startingNum = int(input('Enter the starting number of organisms:'))

#Get the average daily increase
percentIncrease = float(input('Enter the percentage of average daily increase of organisms:'))

#Get the number of days to multiply
number_of_Days = int(input('Enter the number of days to multiply:'))

printFormat = "Day {}\t Population:{}" 
cumPopulation = startingNum

print(printFormat.format(1,cumPopulation))

for number_of_Days in range(number_of_Days):
    cumPopulation *=(1+percentIncrease) # This equals to cumPopulation = cumPopulation * (1 + percentIncrease)
    print(printFormat.format(number_of_Days+2,cumPopulation))

输出:

Enter the starting number of organisms:100
Enter the percentage of average daily increase of organisms:0.2
Enter the number of days to multiply:10
Day 1    Population:100
Day 2    Population:120.0
Day 3    Population:144.0
Day 4    Population:172.8
Day 5    Population:207.36
Day 6    Population:248.832
Day 7    Population:298.5984
Day 8    Population:358.31808
Day 9    Population:429.981696
Day 10   Population:515.9780352
Day 11   Population:619.17364224

答案 1 :(得分:-1)

population = startingNum移至循环外部。