Skip to content

Latest commit

 

History

History
113 lines (84 loc) · 3.31 KB

File metadata and controls

113 lines (84 loc) · 3.31 KB

Java 程序:使用循环显示 Fibonacci 序列

原文: https://beginnersbook.com/2017/09/java-program-to-display-fibonacci-series-using-loops/

Fibonacci 序列是一序列数字,其中数字是前两个数字的总和。从 0 和 1 开始,序列变为0,1,1,2,3,5,8,13,21等。在这里,我们将编写三个程序来打印斐波纳契序列 1)使用for循环 2)使用while循环 3)基于用户输入的数字

要理解这些程序,你应该拥有for循环while循环的知识。

如果您是 java 新手,请参考 java 编程教程开始学习基础知识。

示例 1:使用for循环打印斐波纳契序列

public class JavaExample {

    public static void main(String[] args) {

        int count = 7, num1 = 0, num2 = 1;
        System.out.print("Fibonacci Series of "+count+" numbers:");

        for (int i = 1; i <= count; ++i)
        {
            System.out.print(num1+" ");

            /* On each iteration, we are assigning second number
             * to the first number and assigning the sum of last two
             * numbers to the second number
             */
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
        }
    }
}

输出:

Fibonacci Series of 7 numbers:0 1 1 2 3 5 8

示例 2:使用while循环显示 Fibonacci 序列

public class JavaExample {

    public static void main(String[] args) {

        int count = 7, num1 = 0, num2 = 1;
        System.out.print("Fibonacci Series of "+count+" numbers:");

        int i=1;
        while(i<=count)
        {
            System.out.print(num1+" ");
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
            i++;
        }
    }
}

输出:

Fibonacci Series of 7 numbers:0 1 1 2 3 5 8

示例 3:基于用户输入显示斐波那契序列

该程序根据用户输入的数字显示顺序。例如 - 如果用户输入 10,则此程序显示 10 个数字的序列。

import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {

        int count, num1 = 0, num2 = 1;
        System.out.println("How may numbers you want in the sequence:");
        Scanner scanner = new Scanner(System.in);
        count = scanner.nextInt();
        scanner.close();
        System.out.print("Fibonacci Series of "+count+" numbers:");

        int i=1;
        while(i<=count)
        {
            System.out.print(num1+" ");
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
            i++;
        }
    }
}

输出:

How may numbers you want in the sequence:
6
Fibonacci Series of 6 numbers:0 1 1 2 3 5

查看这些相关的 Java 程序:

  1. Java 程序:寻找因子
  2. Java 程序:检查素数