【问题标题】:Why is this for loop giving me an incorrect output?为什么这个 for 循环给我一个不正确的输出?
【发布时间】:2016-01-12 13:32:39
【问题描述】:

我有一个函数可以告诉我一个数字的因数,然后应该打印它有多少。

factors = 0

def getFactors(n):
    global factors
    for i in range(1,n):
        if n%i==0:
            print(i)
            factors += 1
    print(n, "has", factors, "factors.")

但是,因子的数量似乎是错误的。显然 16 有 6 个因子,尽管它明确列出了 4 个。

>>> getFactors(16)
1
2
4
8
16 has 6 factors.
>>> 

我在这里做错了什么?

【问题讨论】:

  • 你不需要一直到n。显然,一个因子不能大于n/2。因此,您可以使用 range(1, n/2) 节省一半的迭代

标签: python python-3.x if-statement for-loop


【解决方案1】:

在您第一次调用getFactors(16) 时,您将正确获得4。问题可能是您多次调用该函数,并且由于您使用了global factors,因此每次调用该函数时factors 的值都不会重置为0。每次调用函数时,全局变量都会不断变化。

如果您删除 global 变量并将其设为本地函数,它将正常工作

def getFactors(n):
    factors = 0
    for i in range(1,n):
        if n%i==0:
            print(i)
            factors += 1
    print(n, "has", factors, "factors.")

>>> getFactors(16)
1
2
4
8
16 has 4 factors.

【讨论】:

  • 太棒了。谢谢,我完全忘了它需要重置。
  • @Eddie 如果不打印要返回的因子,您可以将函数转换为一行 return [i for i in range(1,n) if n%i == 0](当然也可以使用 yield)
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
相关资源
最近更新 更多