我正在使用 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)
最好在最后使用列表和求和,而不是不断记录数字。
我是一名优秀的程序员,十分优秀!