斐波那契数列 Javascript 做 while 循环

Fibonacci sequence Javascript do while loop

我一直在讨论关于这个主题的各种线程和语言,但我似乎没有找到一个解决方案来设置一个斐波那契数列停止在 100 以下的柱子,在 [=17] 中有一个 do while 循环=].

var fbnci = [0, 1];
var i = 2;

do {
   // Add the fibonacci sequence: add previous to one before previous
   fbnci[i] = fbnci [i-2] + fbnci[i-1];
   console.log(fbnci[i]);
   fbnci[i]++;
} 
while (fbnci[i] < 100);

出于某种原因,上面的代码只运行一次。我应该将 while 条件设置为什么才能继续打印结果,直到它达到最接近 100 的值?

您的代码有误,应该是:

var fbnci = [0, 1], max = 100, index = 1, next;
do {
  index++;
  next = fbnci[index-2] + fbnci[index-1];
  if (next <= max) {
      console.log(next);
      fbnci[index] = next;
  }
} while(next < max);

打印所有小于最大值的 fib 数字的解决方案

对我来说,这是一个不断打印出1的无限循环。你需要增加i而不是增加fbnci[i]:

i++ 而不是 fbnci[i] ++

此外,您仍然会在 while 条件下失败,因为您正在检查一个 nil 值。您需要更改 while 以检查 fbnci[i-1]:

} while(fbnci[i-1]<100);

循环只发生一次,因为到 i=3 时,您的 while 条件无法检查是否 fbci[3] < 100 因为 fbnci[3]undefined.

你可以这样做

var fbnci = [0, 1];
var i = 1;
while(fbnci[i] < 100) {
  fbnci.push(fbnci[i] + fbnci[i-1]);
  i++;
}

console.log(fbnci);