gpt4 book ai didi

javascript - 斐波那契数列 Javascript 执行 while 循环

转载 作者:行者123 更新时间:2023-11-30 16:05:49 24 4
gpt4 key购买 nike

我一直在研究关于这个主题的各种线程和语言,但我似乎没有找到一个解决方案来设置斐波那契数列的栏以在 Javascript 中使用 do while 循环停止在 100 以下.

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 数字的解决方案。

关于javascript - 斐波那契数列 Javascript 执行 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37073964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com