Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript 打印斐波那契数列的程序

用于打印斐波那契数列的 JavaScript 程序

在本例中,您将学习在 JavaScript 中编写斐波那契数列。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript for 循环 JavaScript while 和 do...while 循环
斐波那契数列写成:
0, 1, 1, 2, 3, 5, 8, 13, 21, ...
斐波那契数列是整数序列,其中前两项是0 和1。之后,下一项定义为前两项之和。

示例 1: 最多 n 项的斐波那契数列

// program to generate fibonacci series up to n terms
// take input from the user
const number = parseInt(prompt('Enter the number of terms: '));
let n1 = 0, n2 = 1, nextTerm;
console.log('Fibonacci Series:');
for (let i = 1; i <= number; i++) {
    console.log(n1);
    nextTerm = n1 + n2;
    n1 = n2;
    n2 = nextTerm;
}
输出
Enter the number of terms: 4
Fibonacci Series:
0
1
1
2
在上面的程序中,提示用户输入他们想要的斐波那契数列中的项数。
for 循环迭代到用户输入的数字。
0 首先打印。然后,在每次迭代中,第二项的值存储在变量 n1 中,前两项的总和存储在变量 n2 中。

示例 2: 达到特定数字的斐波那契数列

// program to generate fibonacci series up to a certain number
// take input from the user
const number = parseInt(prompt('Enter a positive number: '));
let n1 = 0, n2 = 1, nextTerm;
console.log('Fibonacci Series:');
console.log(n1); // print 0
console.log(n2); // print 1
nextTerm = n1 + n2;
while (nextTerm <= number) {
    // print the next term
    console.log(nextTerm);
    n1 = n2;
    n2 = nextTerm;
    nextTerm = n1 + n2;
}
输出
Enter a positive number: 5
Fibonacci Series:
0
1
1
2
3
5
在上面的例子中,用户被提示输入一个他们想要打印的斐波那契数列的数字。
前两个词 0 和 1 预先显示。然后,使用 while 循环遍历这些项以找到用户输入的数字为止的斐波那契数列。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4