024-斐波那契数列的Java实现版本

package com;

//斐波那契数列
public class Main {
    //    定义一个递归函数feibo()
    public static int feibo(int n) {

        //        取值为1的时候,返回值为1
        if (n == 1) {
            return 1;

            //            取值为2的时候,返回值仍为1
        } else if (n == 2) {
            return 1;
        } else {

            //            取值不为1或者2的时候,返回值为前两者之和
            return feibo(n - 1) + feibo(n - 2);
        }
    }

    public static void main(String[] args) {

        //建一个循环,打印10以内的所有斐波那契数列值
        int i = 1;
        while (i <= 10) {
            System.out.println(feibo(i));
            i++;
        }

    }
}

运行结果:

"C:\Program Files\Java\jdk1.8.0_131\bin\java.exe"
1
1
2
3
5
8
13
21
34
55

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_31698195/article/details/89841171