Python 2 - "For counting loop"

标签 python for-loop

我正在使用 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/

相关文章:

python - 当一个对象可以等于不同类型的对象时,如何定义 __hash__ ?

python - 使用字典和后续 .sort() 命令更正列表会显示错误的字符串顺序

python - 如何保存循环中子进程的输出(json 文件)

javascript - React/Javascript for 循环 - 当超过数组长度时从 idx 0 开始

python - 循环似乎不遵循顺序

python - PyPI 区分大小写吗?

python - 继承 - __hash__ 在子类中设置为 None

python - matplotlib 中的图形和轴方法

Python 在 Mac OS X 上诅咒鼠标事件

python - 动态嵌套循环-递归