For 循环计数不正确

For Loop not counting properly

练习提示如下:

使用 for 循环从头开始按增量对计数值求和。 使用:total = sum_count(start, increment, count) 参数: start - 范围起始值 (int) increment - 范围增量 (int) count - 范围内值的数量 (int)

我的想法:

def sum_count(start, increment, count):
    total = start
    for i in range(start, count):
        i += increment
        total += i
    else:
        return total

当我使用值 2、2、5 调用和打印函数时,return 应该是 30,但是我只是 return 值 17。我的代码的哪一部分错了吗?

你实际上不需要循环。在数学的帮助下,它可以在 O(1) 时间复杂度内完成。

# Arithmetic Progression
def sum_count(start, increment, count):
    total = 2 * start + (count -1) * increment
    total = (n * total) // 2
    return total
def sum_count(start, increment, count):
    total = 0
    for i in range(start, count):
        i = start + increment
        total += i
    else:
        return total

startincrement 在循环中永远不会改变。他们总是 1.

所以您要添加 (1 + 1) 四次,总共八次。

我不明白你为什么期望 15。

如果您想重复某些内容 x 次,您可以使用一个循环 for _ in range(x),它不会对值 _ 本身做任何事情。

读任务为

Use a for loop to sum count values from start by increment

意味着 count 不是范围的上限——这就是你所做的——而是要加起来的值的数量。因此,对于 count 次,将 start 值增加 increment 并取值的总和。

def sum_count(start, increment, count):
    total = 0
    
    for _ in range(count):
        total += start
        start += increment
   
    return total

首先,您应该注意循环迭代 4 次而不是 5 次,因为您将计数传递为 5。现在如果您想要一个循环以 1,1,5 作为参数获得 15,您可以将代码修改为:

def sum_count(start, increment, count):
    total = 1
    for i in range(start, count):

        i = start + increment
        total = total + i
        start = start + increment

    print("Total: ", total)
    return total

如果总数=0,那么你会得到 14 而不是 15。