CodeGym /Java 博客 /随机的 /Java 中的斐波那契数列
John Squirrels

San Francisco

# Java 中的斐波那契数列

“当我们将从 0 和 1 开始的序列的最后两个连续数字相加时，就形成了斐波那契数列。”

## Java 中的斐波那契数列 [ 迭代法 ]

### 例子

``````public class IterativeFibonacci {

public static void fibonacci(int MAX) {

int firstNumber = 0;
int secondNumber = 1;
int fibonacci = '\0';

System.out.print(firstNumber + " ");
System.out.print(secondNumber + " ");

for (int i = 2; i < MAX; i++) {

fibonacci = firstNumber + secondNumber;
System.out.print(fibonacci + " ");

firstNumber = secondNumber;
secondNumber = fibonacci;
}
}

public static void main(String[] args) {

System.out.println("Print Fibonacci Series Using Iterative Method");
int MAX = 15;
fibonacci(MAX);

}
}``````

## 在 Java 中使用递归的斐波那契数列

### 例子

``````public class RecursiveFibonacci {

// recursive method to return the fibonacci series
public static int fibonacci(int MAX) {

// base case
if (MAX <= 1) {
return MAX;
}

// recursive call
else {
// calculate the last two fibonacci numbers recursively
return fibonacci(MAX - 2) + fibonacci(MAX - 1);
}

}

public static void main(String[] args) {

System.out.println("Print Fibonacci Series Using Recursion in Java");

int MAX = 10;
for (int i = 0; i < MAX; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}``````

## 结论

TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION