import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/*题目要求是这样的·
----------|-----|-----|------|-----|-----|-----|-----|-----|
n(项数) | 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
----------|-----|-----|------|-----|-----|-----|-----|-----|
value(值) | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 |
----------|-----|-----|------|-----|-----|-----|-----|-----|
此处输入项数得出此项的值
例如 输入: 5 7 9 输出:5 13
根据题意不难看出我们的设读入的项数为n
当 n=1 时 值为:1
当 n=2 时 值为:1
当 n=3 时 值为:2
当 n=4 时 值为:3
不难看出规律就是:
当前项n的值为:前两项之和
*/
Scanner input = new Scanner(System.in);
int[] feibor = new int[20]; //定义一数组存储,给个初始空间为20
feibor[1] = 1;
feibor[2] = 1;
for (int i = 3; i < feibor.length; i++) { //为了更加的贴切题目意思我们设置项数从1开启时
feibor[i] = feibor[i - 1] + feibor[i - 2];//当前项等于前两来项之和,我们可以把斐波那数列的序列存到feibor数列中
}
System.out.println("输入你的项数:");
int n = input.nextInt();
System.out.println("第"+n+"项的值为:");
System.out.println(feibor[n]);
}
}
java详解斐波那契数列
最新推荐文章于 2023-07-02 22:28:01 发布