JavaScript中的斐波那契序列 [英] Fibonacci sequence in Javascript

查看:56
本文介绍了JavaScript中的斐波那契序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一般编程人员来说我是一个新手,并且很难理解这个斐波那契数列示例:

I am very new to programming in general and am having a hard time understanding this Fibonacci sequence example:

var fib = [0, 1];
for (var i = 2; i < n; i++) {
    fib[ i ] = fib[ i - 1 ] + fib[ i - 2 ];
    console.log(fib);
}

在第一次迭代中,索引2等于1,非常简单.但是,当我尝试使用i = 3进行第二次迭代时,我得到:

On the first iteration, index 2 is equal to 1, simple enough. But, when I try the second iteration with i = 3, I get:

fib[ 3 ] = fib[ 3 - 1 ] + fib[ 3 - 2 ];  
fib[ 3 ] = fib[ 2 ] + fib[ 1 ]; 
fib[ 3 ] = fib[ 3 ];

我的想法哪里出问题了?到目前为止,我有:

Where am I going wrong with my thinking? So far I have:

var fib = [0,1,1,3]

我知道这是不正确的.

推荐答案

推理代码时,可以从fib[3] = fib[2] + fib[1]跳转到fib[3] = fib[3].这恰好是导致正确陈述的转换,但事实并非如此.此代码将索引2上的值添加到索引1上的值.这与获取索引3上的值不同.这种推理的工作方式如下:

When you are reasoning about the code, you make the jump from fib[3] = fib[2] + fib[1] to fib[3] = fib[3]. This happens to be a transformation that results in a correct statement, but it is not how it works. This code is adding the value at index 2 to the value at index 1. That is not the same as taking the value at index 3. The way this reasoning should work is as follows:

fib = [0, 1]开始.然后,在循环的第一次迭代中,您将得到fib[2] = fib[1] + fib[0].这意味着您将索引0处的值(恰好是0)与索引1处的值(恰好是1)相加,以得到放在末尾的值.数组(1).然后在第二次迭代中,您执行类似的操作,将索引1(仍为1)的值与索引2(也为1)的值相加以获得2,该值位于数组的末尾.这将继续,并且在每次迭代时,您将数组中的最后两个值加在一起以获得下一个值.

You start with fib = [0, 1]. Then in the first iteration of the loop you have fib[2] = fib[1] + fib[0]. This means that you add the value at index 0 (which happens to be 0) to the value at index 1 (which happens to be 1) to get the value that you put at the end of the array (1). Then in the second iteration, you do a similar thing, adding the value at index 1 (still 1) to the value at index 2 (also 1) to get 2, which goes at the end of the array. This continues, and at each iteration you add together the last two values in the array to get the next value.

在JavaScript中,当使用类似fib的数组时,fib[i]引用此数组中从0开始的i值.因此fib[0]是数组中的第一个元素,fib[1]是数组中的第二个元素,依此类推.

In JavaScript, when using an array like fib, fib[i] refers to the ith value in this array, counting from 0. So fib[0] is the first element in the array, fib[1] is the second element in the array, and so on.

这篇关于JavaScript中的斐波那契序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆