[英]Python Geometric Sequence Sum
I would like to calculate the sum of the first 25 numbers in the sequence: 2, 4, 8, 16, 32....我想计算序列中前 25 个数字的总和:2, 4, 8, 16, 32 ....
Why am I receiving an output that says the sum is 50 when it should be higher?为什么我收到的输出显示总和为 50,而它应该更高?
t = 2
sum = 0
for i in range (1, 26) :
sum += t
t *= 2
print("i: ", i, "t: ", t, "sum: ", sum)
i: 25 t: 4 sum: 50
It's just a little typo, in the loop, your adding t
to sum
, when it should be t**i
, and also, it's not good to name variables a replica of a existing keyword, that makes you unable to access that keyword.这只是一个小错误,在循环中,您将t
添加到sum
,什么时候应该是t**i
,而且,将变量命名为现有关键字的副本也不好,这会使您无法访问该关键字。
So do (whole code):这样做(整个代码):
t = 2
s = 0
for i in range (1, 26) :
s += t
t *= 2
print("i: ", i, "t: ", t, "sum: ", s)
Alternatively, you can do:或者,您可以执行以下操作:
t = 2
s = 0
for i in range (1, 26) :
s += t**i
print("i: ", i, "t: ", t**i, "sum: ", s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.