我正在尝试使用变量来查找所有斐波那契,并能够将它们汇总起来(如果可以通过所选变量进行除法)。我也想尝试不使用任何fib()或备注来编写它。
这是我的代码:
endNum = int(raw_input("Enter the end number here "))
divisable_by = int(raw_input("Sum all numbers in the sequence that divide by: "))
# below is the same as "a, b = 0, 1"
a = 0
b = 1
""" gave single letter variables to those above to use in formula below
(longer strings do not seem to work)"""
c = endNum
d = divisable_by
# while b is less than or equal to the ending number, it will loop.
while b <= c:
print b
# below is the same as "a, b = b, a+b"
a_old = a
a = b
b = a_old + b
# the below helps with summing the numbers that are divisable by number chosen.
total = 0
for i in range(a, c):
if i%d == 0:
total += i
#prints text and number calculated above.
print "Sum of all natural numbers that divide by the number you chose"
print "and are less than the other number you chose is: ", total
我可以运行代码,但是得到的答案错误。例如,如果我运行代码以将所有斐波纳契数加起来等于21并被3整除,则得到的答案为“ 0”。答案应该是“ 24 =(3 + 21)”。
一个简单的修改的任何帮助将是巨大的!
您需要先将斐波那契数字添加到列表中,以便稍后在进行除法检查时使用它们。其次,您需要将总数从循环中取出,因为正如kgiannakakis所说,它将始终被0代替。因此,它应如下所示:
endNum = int(raw_input("Enter the end number here "))
divisable_by = int(raw_input("Sum all numbers in the sequence that divide by: "))
# below is the same as "a, b = 0, 1"
a = 0
b = 1
""" gave single letter variables to those above to use in formula below
(longer strings do not seem to work)"""
c = endNum
d = divisable_by
fib_list = []
# while b is less than or equal to the ending number, it will loop.
while b <= c:
print b
fib_list.append(b)
# below is the same as "a, b = b, a+b"
a_old = a
a = b
b = a_old + b
# the below helps with summing the numbers that are divisable by number chosen.
total = 0
for i in fib_list:
if i%d == 0:
total += i
#prints text and number calculated above.
print "Sum of all natural numbers that divide by the number you chose"
print "and are less than the other number you chose is: ", total
此代码还将考虑您提供的最后一个数字,例如,如果您希望的数字是21和3,则总数将为24(21和3除以3)。但这不是您的印刷品所说的“并且小于您选择的其他数字” ...因此,您应考虑将其更改为“小于或等于”
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句