繁体   English   中英

Python中连续数之和

[英]The Sum of Consecutive Numbers in Python

我要做的是获取用户输入并使用循环添加从 1 开始的连续数字,直到总和等于或超过输入。 这是一个练习,所以我尝试在不使用条件 True 或导入任何函数的情况下执行此操作。 只是一个简单的 while 循环。

这就是我所拥有的。

num = int(input("Limit:"))
base = 0
while base < num:
    base += base + 1
    print(base)
    

当我输入 21 时,打印输出是 1 3 7 15 31

不知道如何解决。 任何意见是极大的赞赏。

编辑:很抱歉没有指定,预期的 output 应该只是最终数字,即超过或等于输入的数字。 例如,如果输入为 10,则 output 应为 10。如果输入为 18,则 output 应为 21。

您应该计算专用变量中的连续数字

尝试这个

limit = int(input("Limit:"))
base = 0
number = 1
while base < limit:
    base += number
    number += 1
    print(base)

当输入21时,逐步完成您的代码正在执行的操作。

num = int(input("Limit:"))
base = 0
while base < num:
    base += base + 1
    print(base)

我们知道我们最初的 state 是:

num = 21
base = 0

base小于21 ,所以我们将base添加到1 ,然后将所有这些添加到base+=

num = 21
base = 1

现在,让我们继续:

num = 21
base = 1

num = 21
base = 1 + 1 + 1 = 3

num = 21
base = 3 + 3 + 1 = 7

num = 21
base = 7 + 7 + 1 = 15

number = 21
base = 15 + 15 + 1 = 31

如果您想对一系列数字求和,那么... Python 使用 while 循环使这变得非常简单。 我们需要一个计数器(我们将在每个循环中更新)、结束编号和一个 sum 变量(名称sum已经是一个内置函数)。

num = int(input("Limit:"))
counter = 0
sumNums = 0
while counter < num:
    sumNums += counter
    count += 1
    print(sumNums)

或者我们可以对一个范围求和。

print(sum(range(1, num)))

只是因为我喜欢数学:

num = int(input("Limit:"))
for n in range(1,num):
    s = n * (n + 1) / 2
    if s >= num:
        break
print(int(s))

如果您希望您的预期 output 只是最终数字,只需取消缩进打印语句:

limit = int(input("Limit:"))

base = 0
num = 1

# Each time base is less than limit, add base by num (At the first iteration num is 1), and add num by 1
while base < limit:
    base += num 
    num += 1
print(base)

样品 output:

>>> Limit: 18
21
>>> Limit: 10
10

它必须在打印之前停止。

number = int(input("Limit: "))
x = 1
y = 1
while y < number:
    x +=1
    y +=x
    
print(y)

您必须做 or base = base + 1bas += 1而不是两者,否则您将base + (base + 1)相加是错误的。

但你也可以用同样的方式快速完成:

sum(range(1, num + 1))

暂无
暂无

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

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