连续数字之和

问题描述 投票:0回答:7

我必须编写一个程序,要求用户输入一个限制。然后程序计算连续数字的总和 (1 + 2 + 3 + ...),直到总和至少等于用户设置的限制。

除了结果之外,还应该打印出执行的计算。我应该只使用 while 循环来完成此操作,没有列表或 True 条件。

limit = int(input("Limit:"))
base = 0
num = 0
calc = " "
while base < limit:
    base += num
    num += 1
    calc += f" + {num}"
print(base)
print(f"The consecutive sum: {calc} = {base}")

例如,如果输入为 10,则输出应为 10,其下方应为“连续总和:1 + 2 + 3 + 4 = 10”。如果输入是 18,输出应该是 21,下面应该是“连续和:1 + 2 + 3 + 4 + 5 + 6 = 21。”

现在我可以让它打印最终结果(基数)并让它打印出计算结果,但它打印出的整数太多了。如果输入是 10,它会打印出 1 + 2 + 3 + 4 + 5,而它应该在 5 之前停止。

python loops
7个回答
3
投票

我会避免使用

while
循环并使用
range
代替。您可以通过算术得出最后一项的值。

如果最后一项是 𝑛,则总和 将是 𝑛(𝑛+1)/2,它必须小于或等于输入限制。给定极限,将此方程解为 𝑛,我们得到 𝑛 为 √(1 + 8⋅limit) − 1) / 2

那么程序可以是:

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

n = int(((1 + 8 * limit) ** 0.5 - 1) / 2)

formula = " + ".join(map(str, range(1, n + 1)))
total  = n * (n + 1) // 2
print(f"The consecutive sum: {formula} = {total}")

2
投票

我想到的一种方法是连接每次迭代的值:

limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
calculation = 'The consecutive sum: '
while base < limit:
    calculation += f"{num} + "
    base += num
    num += 1

print(f"{calculation[:-3]} = {base}")
print(base)

#> Limit:18
## The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21
## 21

另一种方法是在每次迭代时打印值,最后不换行(但这里最后有额外的

+
符号):

limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
print('The consecutive sum: ', end='')
while base < limit:
    print(f"{num} + ", end='')
    base += num
    num += 1

print(f"= {base}")
print(base)

#> Limit:18
## The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 + = 21
## 21

0
投票

可能有一种更有效的方法来写这个,但这就是我想到的......

sum = 0
long_output = []

for i in range(limit + 1):
  sum += i
  long_output.append(str(i))

print("The consecutive sum: {} = {}".format(' + '.join(long_output), sum))

不断将东西放入列表中,然后再加入它们。

i
必须转换为
str
类型,因为 join 仅适用于字符串

注意:输出从

0
开始,以考虑
limit
可能为 0(我不知道你的约束是什么,如果有的话)

编辑:根据@Copperfield 的建议进行更新


0
投票

你们现在/曾经非常接近。尝试重新安排 while 语句中的后续执行。我也觉得这个任务很难。尝试将计算行移动为“while”之后的第一个语句。


0
投票

另一种方法是添加

if
语句:

if base< num :
   calc += f" + {num}"

0
投票
# Write your solution here
number=0
base=0
total=0
ntotal=""
code=int(input("Limit:"))
while base<code: 
    number+=1 #increment the consecutive numbers
    if base==0:
        ntotal = f"{ntotal}{number}" #ignore the first null string of ntotal ""
    else:
        ntotal = f"{ntotal}+{number}" #concat the strings
    base+=number #increment after the if statement, else it will always add the null string and give as +1+2...
    
print(f"The consecutive sum:{ntotal}={base}")

-1
投票

这里是打印计算的示例

limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
msg = ""
while base < limit:
    msg = msg + str(num) + "+"
    base += num
    num += 1
msg =  msg[:-1] + "=" + str(limit) 
print(msg)

如果

limit = 21
那么输出将是

1+2+3+4+5+6=21
© www.soinside.com 2019 - 2024. All rights reserved.