gpt4 book ai didi

Python 2 - "For counting loop"

转载 作者:太空宇宙 更新时间:2023-11-03 17:05:10 26 4
gpt4 key购买 nike

我正在使用 python 2 为学校开发一个项目,但我在解决以下问题之一时遇到了很多麻烦:

Write a program that computes the following sum: sum = 1.0/1 + 1.0/2 + 1.0/3 + 1.0/4 + 1.0/5 + .... + 1.0/N N is an integer limit that the user enters.

For example:
Enter N: 4
Sum is: 2.08333333333

我目前编写的代码是:

NumOfN = int(input("What is N? : "))
total = 0
for i in range (NumOfN):
NextNum = 1.0/(NumOfN)
total = NextNum
NumOfN = NumOfN-1
print "the sum is", total

但是,每当我运行此程序时,我都会得到输出“1.0”,任何帮助将不胜感激。

-谢谢。

最佳答案

您没有使用自身和 NextNum 来增加 total。我将 total = NextNum 更改为 total += NextNum:

NumOfN = int(input("What is N? : "))
total = 0
for i in range(NumOfN):
NextNum = 1.0/(NumOfN)
total += NextNum
NumOfN = NumOfN-1
print "the sum is ", total

或更简单地说:

NumOfN = int(input("What is N? : "))
runningTab = []
for i in range(NumOfN, -1, -1):
if i != 0:
runningTab.append(1.0/(i))

print "the sum is ", sum(runningTab)

最好在最后使用列表和求和,而不是不断记录数字。

关于Python 2 - "For counting loop",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34646679/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com