[英]How can i get sum of all the numbers that this program prints?
B = 1
A = 3
C = 1
while C < 1000:
B = B + 1
C = A * B
print (C)
This is the code and i want to get the sum of the numbers that it prints 这是代码,我想获取它打印的数字的总和
Here is a possibility, 这是可能的
B = 1
A = 3
C = 1
D = 0
while C < 1000:
B = B + 1
C = A * B
D += C
print (C)
# sum of all printed numbers
print(D)
B
runs over all the integers from 2
to 334
; B
遍历从2
到334
所有整数; you only need the sum of all integers from 2
to 334
(which is well known: average * number of elements) and then multiply it by A
: 您只需要从
2
到334
的所有整数之和(众所周知:平均值*元素数),然后将其乘以A
:
A = 3
B_max = 334 # ~ (1000 // A) + ...
res = A * (B_max + 2) * (B_max - 1) // 2
# 167832
you just need to make sure you get B_max
right... 您只需要确保您正确设置了
B_max
...
there is no reason for a loop at all if that is all you need to do. 如果您需要做的就是根本没有循环的理由。
define a list outside while: 在以下时间之外定义列表:
dataList = []
then add C in that list: 然后在该列表中添加C:
while C < 1000:
B = B + 1
C = A * B
dataList.append(C)
then find sum: 然后求和:
print(sum(dataList))
for me, your goal is not clear. 对我来说,您的目标并不明确。 can you explain it more for me to be able to help you?
您能为我提供更多帮助的方法吗?
PS. PS。 your B = B + 1 can be simplified to:
您的B = B +1可简化为:
B += 1
B + = 1
You should declare SUM first: 您应该先声明SUM:
SUM=0 总和= 0
And at the end of while loop after print message, add 然后在打印消息后的while循环末尾添加
SUM = SUM + C SUM = SUM + C
And thats all, simplest possible way. 这就是最简单的方法。
B = 1
A = 3
C = 1
total = 0
while C < 1000:
B = B + 1
C = A * B
print(C)
total+=C
print("Sum is : ",total)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.