查找给定数字的斐波那契上限和下限

时间:2019-05-18 23:07:24

标签: python python-3.x

我在网站上找到了该代码,但我不太了解它的工作原理或找到给定数字的斐波那契上下边界。

我想用一个类似x = 6

的例子来理解代码的运行方式。
def fib_intervall(x):
    """ returns the largest fibonacci
    number smaller than x and the lowest
    fibonacci number higher than x"""
    if x < 0:
        return -1
    (old,new, lub) = (0,1,0)
    while True:
        if new < x:
            lub = new 
            (old,new) = (new,old+new)
        else:
            return (lub, new)

while True:
    x = int(input("Your number: "))
    if x <= 0:
        break
    (lub, sup) = fib_intervall(x)
    print("Largest Fibonacci Number smaller than x: " + str(lub))
    print("Smallest Fibonacci Number larger than x: " + str(sup)

1 个答案:

答案 0 :(得分:0)

首先,您必须检查每一行代码,如果您确实想理解,请尝试更改某些行。

答案:

步骤1。您将进入无限while循环,并将6分配给x。

步骤2。X <= 0为假,因此将调用fib_intervall(6),然后将结果分配给lub,sub。

步骤3:在fib_intervall中:

{1-如果语句为false(6> 0。

2-旧= 0新= 1润滑= 0分配完成。

3-将执行另一个无限循环:

new是1和1 <6,所以if语句将被执行。 old(0)将是new(1),而new将是old + new

[旧= 0新=旧+新。]

循环将继续如下

[旧= 1新= 2]-> [旧= 2新= 3]-> [旧= 3新= 5]-> [旧= 5新= 8]

在最后一次赋值后new = 8> 6,因此将执行else语句,函数将返回(5,8),这是6的斐波那契边界。}

步骤4、5将打印lub变量。 8将打印有sup变量:

小于x的最大斐波那契数:5

大于x的最小斐波那契数:8