我有一个函数可以告诉我一个数的因数,然后打印它有多少。
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.
>>>
我做错了什么?
最佳答案
第一次调用 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.
关于python - 为什么这个 for 循环给我一个不正确的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33125716/