gpt4 book ai didi

python - Python 中的 while 循环和斐波那契(不导入或使用 "fib")

转载 作者:太空宇宙 更新时间:2023-11-03 18:39:47 28 4
gpt4 key购买 nike

我正在尝试使用变量来查找所有斐波那契数,并能够在可被所选变量整除的情况下对它们进行求和。我还想尝试在不使用任何 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)”。

任何简单修改的​​帮助都会很棒!

最佳答案

您在每个循环中将总计重置为 0。将其移出循环。也不要在每个循环中测试范围。这也会给你错误的结果。仅测试找到的新号码。

关于python - Python 中的 while 循环和斐波那契(不导入或使用 "fib"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20757246/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com