Java 实例 使用循环显示 Fibonacci 序列

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

示例 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
赞(0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

Java 实例