English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriais Básicos de Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Tratamento de Exceções Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java程序显示斐波那契数列

Java Examples Comprehensive

在该程序中,您将学习在Java中使用for和while循环显示斐波那契数列。您将学习如何显示最多包含特定术语或数字的序列。

斐波那契数列是一个序列,其中下一项是前两项的总和。斐波那契数列的前两项是0,然后是1.

数列: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...

Example1:使用for循环显示斐波那契数列

public class Fibonacci {
    public static void main(String[] args) {
        int n = 10, t1 = 0, t2 = 1;
        System.out.print("First " + n + "terms: ");
        for (int i = 1; i <= n; ++i)
        {
            System.out.print(t1 + " + ");
            int sum = t1 + t2;
            t1 = t2;
            t2 = sum;
        }
    }
}

When running the program, the output is:

0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 +

No programa acima, o primeiro termo (t1) e o segundo termo (t2) inicializados respectivamente como o zero e1dos dois primeiros termos.

Em seguida, o loop for itera até n (número de itens), mostrando o valor armazenado na variável t1da soma dos dois primeiros termos.

Você também pode usar o loop while do Java para gerar a sequência de Fibonacci.

Example2:使用while循环显示斐波那契数列

public class Fibonacci {
    public static void main(String[] args) {
        int i = 1, n = 10, t1 = 0, t2 = 1;
        System.out.print("First " + n + "terms: ");
        while (i <= n)
        {
            System.out.print(t1 + " + ");
            int sum = t1 + t2;
            t1 = t2;
            t2 = sum;
            i++;
        }
    }
}

A saída é a mesma que o programa acima.

No programa acima, diferentemente do loop for, devemos aumentar o valor de i dentro do corpo do loop.

Although both programs are technically correct, it is best to use a for loop in this case. This is because the number of iterations (from1to n) is known.

Example3: Display the maximum number of given numbers (not items) in the Fibonacci sequence

public class Fibonacci {
    public static void main(String[] args) {
        int n = 100, t1 = 0, t2 = 1;
        
        System.out.print("Upto ", + n + ": ");
        while (t1 <= n)
        {
            System.out.print(t1 + " + ");
            int sum = t1 + t2;
            t1 = t2;
            t2 = sum;
        }
    }
}

When running the program, the output is:

Upto 100: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 +

This program will display the sequence up to the given number (100), rather than displaying the sequence until a specific number.

For this, we just need to compare the last two numbers (t1). And n sum.

If t1Print t less than or equal to n1.

Java Examples Comprehensive