我正在尝试将斐波那契数字打印到n。由于某种原因,下面的代码打印出两次最后一个数字,请帮助。
function fibonacci(n) {
let i;
const fib = [];
fib[0] = 0;
fib[1] = 1;
for (i=2; i<n; i++) {
fib[i] = fib[i-2] + fib[i-1];
fib.push(fib[i]);
}
console.log( fib );
}
答案 0 :(得分:2)
您需要在索引处分配值,或者分配总和。
function fibonacci(n) {
let i;
const fib = [];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i < n; i++) {
fib[i] = fib[i - 2] + fib[i - 1]; // either this assignm. or the next line only
// fib.push(fib[i - 2] + fib[i - 1]);
}
return fib;
}
console.log(fibonacci(8));
答案 1 :(得分:2)
function fibonacci(n) {
let i;
const fib = [];
fib[0] = 0;
fib[1] = 1;
for (i=2; i<n; i++) {
fib[i] = fib[i-2] + fib[i-1];
// Remove the following line as you are already assigning the value in the line above.
//fib.push(fib[i]);
}
console.log( fib );
}
答案 2 :(得分:2)
只需删除
fib.push(fib[i]);
然后
function fibonacci(n) {
let i;
const fib = [];
fib[0] = 0;
fib[1] = 1;
for (i=2; i<n; i++) {
fib[i] = fib[i-2] + fib[i-1];
}
}
fibonacci(7);
给出输出:
[ 0, 1, 1, 2, 3, 5, 8 ]
发表评论后,我修改了代码,以便将其用于i=1
"use strict";
function fibonacci(n) {
let i;
const fib = [];
fib[0] = 0;
for (i=1; i<n; i++) {
fib[i] = ((fib[i-2]!==undefined)?fib[i-2]:1) + fib[i-1];
}
console.log(fib)
}
fibonacci(1);
fibonacci(2);
fibonacci(7);
[ 0 ]
[ 0, 1 ]
[ 0, 1, 1, 2, 3, 5, 8 ]
我删除了fib[1]
的定义,总而言之,只有当i
为1
时才会为fib[i-2]
元素使用值undefinted
,这意味着此条件仅在i=1
时才会满意,因为循环从1
开始,但表fib
没有密钥-1
。如果i
大于1
,则fib[i-2]
存在且等式具有较早的值。
答案 3 :(得分:1)
你做错了:首先在数组中创建第n个元素,然后在数组中推送相同的元素,复制它。你不需要推送命令。
正确的代码是:
function fibonacci(n) {
let i;
const fib = [];
fib[0] = 0;
fib[1] = 1;
for (i=2; i<n; i++) {
fib[i] = fib[i-2] + fib[i-1];
}
console.log( fib );
}
fibonacci(5);
&#13;