[英]Function to find the factors of a negative number
我需要编写一个函数来查找负数的因子并将它们输出到列表中。 我该怎么做? 我可以让我的函数做正数(见下文)而不是负数。
#Finds factors for A and C
def factorspos(x):
factorspos = [1,-6];
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
factorspos.append(i)
print(i)
我尝试更改循环计数的值,因此它将从选择的数字计数为 1(下面的代码),但仍然没有产生任何结果:(
#Finds factors for A and C
def factorspos(x):
factorspos = [int(-6),1];
print("The factors of",x,"are:")
for i in range(int(-6), x + 1):
if x % i == 0:
factorspos.append(i)
print(i)
我已将 Cco 更改为固定数字。
#Finds factors for A and C
def factorspos(x):
Cco = -6
factorspos = [int(Cco),1];
print("The factors of",x,"are:")
for i in range(int(Cco), x + 1):
if x % i == 0:
factorspos.append(i)
print(i)
return factorspos
def factorspos(x):
x = int(x)
factorspos = []
print("The factors of",x,"are:")
if x > 0: # if input is postive
for i in range(1,x+1):
if x % i == 0:
factorspos.append(i)
print(i)
return factorspos
elif x < 0: #if input is negative
for i in range(x,0):
if x % i == 0:
factorspos.append(i)
print(i)
return factorspos
print(factorspos(12)) #outputs [1, 2, 3, 4, 6, 12]
print(factorspos(-12)) #outputs [-12, -6, -4, -3, -2, -1]
您实际上非常接近解决您的问题。 我冒昧地为您拥有的功能添加了一个额外的功能。 基本上我添加了一个条件检查器来查看输入x
是正数还是负数,该函数做了两件不同的事情。 他们所做的是你提供的,但清理干净了。
注意事项range()
从第一个数字开始,到第二个参数后一个数字结束。 range(1,10)
会给你 1 到 9。这就是为什么如果你看,范围从 x 到 0 的负部分,因为那会说 x 到 -1。 在正部分,它将从 1 变为 x+1,因为 +1 确保我们包含我们的输入。 剩下的你知道的,你写的好; 如果不能随意提问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.