【问题标题】:Printing total using for loop使用 for 循环打印总计
【发布时间】:2019-08-10 12:10:44
【问题描述】:

我正在尝试通过代码 1 而不是代码 2 来获得 1、2、3、4 的总数。有人可以指出为什么代码 2 返回 4 而不是 10?

代码 1:

total = 0
for i in range(1,5):
    total = total + i

print(total)
10

代码 2:

total = 0
for i in range(1,5):
    newtotal = total + i

print(newtotal)
4

【问题讨论】:

  • 你认为代码2最后一次迭代中total的值是多少?

标签: python-3.x for-loop


【解决方案1】:

这是因为在 code2 中总没有更新,它总是为零,因为你将它初始化为 0 所以每次在 for 循环中我都会像这样更新

newtotal = 0+1 = 1
next time
newtotal = 0+2 = 2
nex time
newtotal = 0+3 = 3
nex time
newtotal = 0+4 = 4

但在代码 1 中,您每次都使用语句更新总的值

总计 = 总计 + i

first time
total = 0+1 = 1
//now total is 1
next time
total = 1+2 = 3
next time
total = 3+3 = 6
next time
total = 6+4 = 10

因此答案是 10

【讨论】:

    【解决方案2】:

    因为在 CODE 2 中,每次迭代的总数为 0。

    total = 0
    newtotal = 0
    for i in range(1,5):
        total = newtotal
        newtotal = total + i
    
    print(newtotal)
    

    现在我们在这里更新 total 的值

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 2013-02-20
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 2022-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多