对于循环似乎要添加更多的变量而不是它应该

360*_*mer 2 python python-3.x

所以,我想创建一个循环,在任何给定的时间内增加项目的成本,同时记录实例的总成本.问题在于,无论何时执行程序,输出似乎都应该超出应有的范围,如果我将变量的值更改cost为10,那么它似乎比它应该稍微多一点.这是代码:

amount = 3
cost = 0
increase = 10

for i in range(amount):
  cost += increase
  increase += increase


total = cost
print(total)
Run Code Online (Sandbox Code Playgroud)

cost = 0总数变为70,当我认为它应该是60,然后当cost = 10总数变为80时,我认为它应该是90.

任何帮助将不胜感激 - 抱歉提出这样一个愚蠢的问题.这可能是一个非常简单的修复.

Pru*_*une 5

increase每次循环都会加倍.我不确定你期望得到60分和90分的成绩.我print在循环的底部插入了一个简单的:

for i in range(amount):
  cost += increase
  increase += increase
  print("TRACE", cost, increase)
Run Code Online (Sandbox Code Playgroud)

输出:

TRACE 10 20
TRACE 30 40
TRACE 70 80
70
Run Code Online (Sandbox Code Playgroud)

这会让你解决问题吗?也许你需要的是增加cost一个线性升级的数量:

for i in range(amount):
  cost += increase
  increase += 10
Run Code Online (Sandbox Code Playgroud)

输出:

TRACE 10 20
TRACE 30 30
TRACE 60 40
60
Run Code Online (Sandbox Code Playgroud)