You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询查找给定数字上下斐波那契边界的代码运行逻辑(示例x=6)

理解斐波那契边界查找代码的运行机制(以x=6为例)

我来帮你彻底搞懂这段代码的运行逻辑,咱们就拿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))

先搞懂核心变量和整体功能

这段代码的核心是fib_intervall函数,它的作用是输入一个正整数x,返回两个值:

  • 小于x的最大斐波那契数(存在变量lub里,是Lower Upper Bound的缩写)
  • 大于等于x的最小斐波那契数(存在变量new里)

函数里的三个关键变量:

  • old:斐波那契序列里的前一个数
  • new:斐波那契序列里当前生成的数
  • lub:用来临时记录目前找到的小于x的最大斐波那契数

外层的while True循环很简单:持续接收用户输入,直到输入非正数时退出程序。

以x=6为例,一步步走函数流程

当你输入6后,程序调用fib_intervall(6),执行过程如下:

  1. 初始检查:x=6≥0,跳过if x<0的错误分支。
  2. 变量初始化:old=0,new=1,lub=0(先默认最小的斐波那契数0作为初始候选)。
  3. 进入无限循环,开始生成斐波那契数:
    • 第一次循环:
      • 判断new < x?1 < 6 → 是。
      • 更新lub = new → lub=1(现在记录下第一个小于6的斐波那契数)。
      • 更新斐波那契数对:(old, new) = (new, old+new) → old=1,new=0+1=1。
    • 第二次循环:
      • new=1 <6 → 是。
      • lub保持1(因为new没变大,不需要更新)。
      • 更新斐波那契数对:(old,new)=(1,1+1=2) → old=1,new=2。
    • 第三次循环:
      • 2 <6 → 是。
      • lub=2(现在记录下更大的小于6的斐波那契数)。
      • 更新斐波那契数对:(old,new)=(2,1+2=3) → old=2,new=3。
    • 第四次循环:
      • 3 <6 → 是。
      • lub=3。
      • 更新斐波那契数对:(old,new)=(3,2+3=5) → old=3,new=5。
    • 第五次循环:
      • 5 <6 → 是。
      • lub=5(这是目前找到的最接近6且小于它的斐波那契数)。
      • 更新斐波那契数对:(old,new)=(5,3+5=8) → old=5,new=8。
    • 第六次循环:
      • 判断new <x?8 <6 → 否。
      • 触发else分支,直接返回(lub, new) → 也就是(5,8)。

最终输出结果

外层循环拿到返回值后,会打印:

Largest Fibonacci Number smaller than x: 5
Smallest Fibonacci Number larger than x: 8

逻辑总结

简单说,这个函数就是从斐波那契序列的开头(0,1)开始不断生成下一个数:

  • 只要生成的数还小于x,就把它记为当前的lub(因为它是目前最大的小于x的数);
  • 一旦生成的数大于等于x,就停止循环,返回之前记录的lub和当前的数——这俩就是你要找的上下边界。

内容的提问来源于stack exchange,提问作者dinesh solanki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:44:45