如何以增量将当前算法实现为for循环?
我需要循环遵循以下代码的算法。每个循环都应花费第一天(2),并将平均值(.3)添加到其中。
startOrganism = 2
startOrganism = int(input("Starting number of organisms:"))
dailyInc = .3
dailyInc = float(input("Average daily increase (percent): "))
numberDaysMulti = 10
numberDaysMulti = int(input("Number of days to multiply: "))
for x in range(numberDaysMulti):
(Needs to be below)
Day 1 2
Day 2 2.6
Day 3 3.38
etc.
I need the loop to follow the algorithm of the code below. Every loop should take the first day (2) and add the average (.3) to it.
startOrganism = 2
startOrganism = int(input("Starting number of organisms:"))
dailyInc = .3
dailyInc = float(input("Average daily increase (percent): "))
numberDaysMulti = 10
numberDaysMulti = int(input("Number of days to multiply: "))
for x in range(numberDaysMulti):
(Needs to be below)
Day 1 2
Day 2 2.6
Day 3 3.38
etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好的,我假设用户将每天增加百分比为
0.3
,而不是30
:示例输出:
Ok, I've assumed that the user will input the percent daily increase as
0.3
as opposed to30
:Sample Output:
可以使用以下公式来数学处理这种计算:
其中
ground_rate
是您的情况下的每单位时间增加百分比。然后,简单地打印出每天的价值就成为一个问题。(这几天使用零索引。也就是说,“第0天”将是您的首发号码。索引以这种方式节省您的错误,但是您可以将打印语句更改为
{day {day { + 1}
是向用户隐藏此数据结构。)有一种替代方法,您在每个循环中携带状态,在您迭代时第二天计算。但是,我建议您将计算和显示的关注点分开 - 这种本能将为您提供良好的服务。
grounts = [...对于范围(周期)的一天]
是一个列表理解,它的工作方式与单行的前循环。This sort of computation can be handled mathematically, using the following formula:
Where the
growth_rate
is the percent increase per unit of time, in your case days. Then it becomes a matter of simply printing out the value for each day.(This uses a zero-index for the days. That is, 'day 0' will be your starting number. Indexing this way saves you off-by-one errors, but you can change the print statement to be
{day + 1}
to hide this data structuring from the user.)There is an alternative method where you carry state in each loop, calculating the next day as you iterate. However, I'd recommend separating the concern of calculation and display - that instinct will serve you well going forward.
The
growth = [... for day in range(period)]
is a list comprehension, which works much like a one-line for-loop.