斐波那契数列java完整代码
时间: 2023-10-17 17:26:18 浏览: 99
以下是使用数组循环、递归和递归方法实现斐波那契数列的完整代码:
使用数组循环:
```java
public class test4 {
public static void main(String[] args) {
int[] arr = new int = 1;
arr = 1;
for (int i = 2; i < arr.length; i++) {
arr[i = arr[i - 1 + arr[i - 2];
}
String s = Arrays.toString(arr);
System.out.println("前十个斐波那契数是:" + s);
}
}
```
使用递归方法:
```java
public class Demo2 {
private static int getFibo(int i) {
if (i == 1 || i == 2)
return 1;
else
return getFibo(i - 1) + getFibo(i - 2);
}
public static void main(String[] args) {
System.out.println("斐波那契数列的前20项为:");
for (int j = 1; j <= 20; j++) {
System.out.print(getFibo(j) + "\t");
if (j % 5 == 0)
System.out.println();
}
}
}
```
使用递归的方法:
```java
public class test2 {
public static void main(String[] args) {
for (int counter = 1; counter <= 10; counter++) {
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
}
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
}
```
请注意,以上代码是完整的斐波那契数列的实现。不同的代码使用了不同的方法来计算斐波那契数列,你可以根据自己的需要选择其中一个方法来使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [斐波那契数列java代码实现](https://blog.csdn.net/weixin_48720080/article/details/120212504)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [斐波那契数列——java代码实现](https://blog.csdn.net/lb812913059/article/details/83313893)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文