简体   繁体   English

python中的for循环和楼层划分

[英]For loops and floor division in python

I just had a question about this for loop我只是有一个关于这个 for 循环的问题

total = 0

for x in range(1,15,3):

    total += x

    total //= 2

print(total)

So the answer is 10 when I run it, but when I try to do it by hand I get 17. For example when I add up all the x's it will be 35. Then I floor divide by 2 which will give me 35//2 =17.所以当我运行它时答案是 10,但是当我尝试手动完成时,我得到 17。例如,当我将所有 x 相加时,它将是 35。然后我将其除以 2,这将给我 35// 2 = 17。 I honestly don't know why its 10.老实说,我不知道为什么是 10。

Your code is computing sums like this:您的代码正在计算这样的总和:

(((0 + x1) / 2 + x2) / 2 + x3) / 2 + ...

You can perform the division to see that this is not the same as (0 + x1 + x2 + x3 + ...) / 2 .您可以执行部门看,这是一样的(0 + x1 + x2 + x3 + ...) / 2 For example:例如:

((x1/2 + x2)/2 + x3)/2 == x1/8 + x2/4 + x3/2

Just place total //= 2 outside the for loop.只需将 total //= 2 放在 for 循环之外。 your code is finding the floor value of total in every iteration and overwriting total.您的代码在每次迭代中找到 total 的下限值并覆盖 total。

total = 0
for x in range(1, 15, 3):
    total += x
total //= 2
print(total)

In Python the tab matters.在 Python 中,选项卡很重要。 The following will give you 17下面给你17

total = 0

for x in range(1,15,3):

    total += x

total //= 2

print(total)

It gets floored in the loop, you're adding up the floored values.它在循环中被压低,您将被压低的值相加。

You need to floor the sum, after the loop is done.循环完成后,您需要对总和进行下底。

total = 0
for x in range(1, 15, 3):
    total += x
total //= 2
print(total)
total = 0

for x in range(1,15,3):
    total += x

    a = total//2



print(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM