簡體   English   中英

循環的新手問題

[英]Newbie issue with loops

我為嘗試在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)

我可以產生每個的商,但是卻迷失了如何有效地求和。

為了提高效率:

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的提示;)

您快到了,所以我給您一些提示。

# 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

如果要查看更多的Pythonic(idomatic)解決方案,請參見zhangxaochen的答案。 ;)

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

請注意,您將要進行一些四舍五入,並且可能會得到您所期望的答案。

這樣做可以跟蹤求和。

total = 0

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

print(total)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM