新手循环问题

2024-09-29 04:22:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我在尝试用Python(3)来完成下面的任务时脑子都快死了。请帮忙。在

编写一个循环来计算以下一系列数字的总和:1/30+2/29+3/27+⋯+29/2+30/1。在

for numerator in range(1, 31, 1):
    denominator = (31 - numerator)
    quotient = numerator / denominator
    print(quotient)

我能算出每一个的商,但不知道如何有效地求和。在


Tags: inforrange数字print总和quotient脑子
3条回答
total = 0
for numerator in range(1, 31, 1):
    denominator = (31 - numerator)
    quotient = numerator / denominator
    print(quotient)
    total += quotient
print/return(total)

你可能还没有意识到答案。在

你快到了,我给你一些提示。在

# initialize a total variable to 0 before the loop

for numerator in range(1, 31, 1):
    denominator = (31 - numerator)
    quotient = numerator / denominator
    print(quotient)
    # update the total inside the loop (add the quotient to the total)

# print the total when the loop is complete

如果您想看到一个更具Python(idomatic)的解决方案,请参阅zhangxaochen的答案。;)

为了提高效率:

In [794]: sum(i*1.0/(31-i) for i in range(1, 31)) # i*1.0 is for backward compatibility with python2
Out[794]: 93.84460105853213

如果必须在循环中显式地执行此操作,请参见@Bill's hints;)

相关问题 更多 >