📅  最后修改于: 2023-12-03 14:55:03.559000             🧑  作者: Mango
斐波那契数列指的是这样一个数列:0、1、1、2、3、5、8、13、21、34...,即每个数字都是前两个数字之和。
斐波那契数列在算法和编程中有着广泛的应用,例如:
下面是一个示例的斐波那契数字程序,使用不同的语言实现:
def fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
sequence = [0, 1]
while len(sequence) < n:
next_num = sequence[-1] + sequence[-2]
sequence.append(next_num)
return sequence
n = 10
fib_seq = fibonacci(n)
print(fib_seq)
function fibonacci(n) {
if (n <= 0) {
return [];
} else if (n === 1) {
return [0];
} else if (n === 2) {
return [0, 1];
} else {
var sequence = [0, 1];
while (sequence.length < n) {
var nextNum = sequence[sequence.length-1] + sequence[sequence.length-2];
sequence.push(nextNum);
}
return sequence;
}
}
var n = 10;
var fibSeq = fibonacci(n);
console.log(fibSeq);
import java.util.ArrayList;
import java.util.List;
public class Fibonacci {
public static List<Integer> fibonacci(int n) {
List<Integer> sequence = new ArrayList<>();
if (n <= 0) {
return sequence;
} else if (n == 1) {
sequence.add(0);
return sequence;
} else if (n == 2) {
sequence.add(0);
sequence.add(1);
return sequence;
} else {
sequence.add(0);
sequence.add(1);
while (sequence.size() < n) {
int nextNum = sequence.get(sequence.size()-1) + sequence.get(sequence.size()-2);
sequence.add(nextNum);
}
return sequence;
}
}
public static void main(String[] args) {
int n = 10;
List<Integer> fibSeq = fibonacci(n);
System.out.println(fibSeq);
}
}
在上述示例程序中,通过逐个计算前两个数字之和,来生成斐波那契数列,并将结果输出。
请根据自己所用编程语言的特点,参考上述示例程序,编写适合的斐波那契数字程序。