简体   繁体   English

我如何获得该程序打印的所有数字的总和?

[英]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遍历从2334所有整数; 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 : 您只需要从2334的所有整数之和(众所周知:平均值*元素数),然后将其乘以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.

相关问题 如何编写一个程序来打印用户必须输入的十个数字的总和 - How to write a program that prints the sum of ten numbers that the user has to enter 编写一个程序,打印出文件中数字的总和 - Write a program that prints out the sum of the numbers in the file 如何获取Python范围函数中所有数字的总和? - How do I get the sum of all numbers in a range function in Python? 如何使用 python 计算文本中所有数字的总和? - How can i calculate sum of all numbers in text with python? 我如何编写一个 python 程序,打印出所有至少三个字符长的子字符串? - How can I write a python program, which prints out all the substrings which are at least three characters long? 如何在特定条件下获得回文数的总和? - How can i get sum of Palindromic numbers with specific conditions? “如何修改以下程序,使其以特定格式打印?” - “How can I modify the below program so it prints in a specific format?” 如何编写 python 程序来打印用逗号分隔的一串数字的总和? - How can I write a python program to print the sum of a string of numbers that are separated by a comma? 我如何编写一个基本程序,要求输入一个数字,然后打印出从 1 到该数字的总和? - How do i write a basic program that asks for a number and then prints out the sum from one to the number? 我将如何创建一个程序,在添加每个数字后打印总和 [暂停] - how would i create a program where it prints the sum after each number added [on hold]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM