斐波那契數列(Java)

1999LIJIAN發表於2024-06-13

b. 斐波那契數列(Fibonacci Sequence) 實現一個函式,計算斐波那契數列的第 n 項。

plaintextCopy code
Input: 一個非負整數 n Output: 斐波那契數列的第 n 項

解答程式碼:

import java.util.Scanner;

/**
 * @Author LIJIAN
 * @Date 2024/6/10 21:22
 */
public class FibonacciSequence {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("請輸入要計算的斐波那契數列的項數:");
        int n = scanner.nextInt();
        int result = Fibonacci(n);
        System.out.println("斐波那契數列的第 " + n + " 項是:" + result);
    }

    public static int Fibonacci(int n) {
        if (n <= 1) {
            return n;
        }
        int num1 = 0;
        int num2 = 1;
        int FibonacciSum = 0;
        for (int i = 2; i <= n; i++) {
            FibonacciSum = num1 + num2;
            num1 = num2;
            num2 = FibonacciSum;
        }
        return FibonacciSum;
    }
}

相關文章