Fibonacci序列使用For循环

huangapple go评论48阅读模式
英文:

Fibonacci sequence using For Loop

问题

这个问题是编写一个输出第n个斐波那契数的程序。

我不明白为什么在range()中需要n-1

def fib_linear(n: int) -> int:
    if n <= 1:  # 第一个斐波那契数是1
        return n

    previousFib = 0
    currentFib = 1

    for i in range(n - 1):  # 这里为什么是n-1?
        newFib = previousFib + currentFib
        previousFib = currentFib
        currentFib = newFib

    return currentFib
英文:

This qustion is to Write a program that outputs the nth Fibonacci number.

I dont understand why do we need n-1 in the range()

def fib_linear(n: int) -&gt; int:
    if n &lt;= 1:  # first fibonacci number is 1 
        return n
 
    previousFib = 0
    currentFib = 1
 
    for i in range(n - 1):  
        newFib = previousFib + currentFib
        previousFib = currentFib
        currentFib = newFib
 
    return currentFib

答案1

得分: 0

因为你想要输出第n个斐波那契数。如果你用“n”代替“n-1”。那么你将得到第n+1个斐波那契数。

英文:

Cause you wanna output n-th fibonacci number. If you put "n" instead of "n-1". Then you'll get n+1-th fibonacci number.

huangapple
  • 本文由 发表于 2023年4月10日 19:52:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976854.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定