gpt4 book ai didi

java - 使用斐波那契数列的基本数组列表

转载 作者:行者123 更新时间:2023-11-30 07:55:50 24 4
gpt4 key购买 nike

我希望这个程序采用一个数组列表“max”,其大小由用户创建。然后程序使用斐波那契数列将所有小于用户输入创建的数组列表“max”的斐波那契数存储在数组列表中。

import java.util.*;
import javax.swing.*;

public class FibonacciArrayList {

public static ArrayList<Integer> Fibonacci (Integer Max){

ArrayList<Integer> A = new ArrayList<Integer>();
int n0;
int n1;
int n2;

for(int i= 0; i = max; i++){
n2= n1 + n0;
system.out.println(n2);
n0=n1;
n1=n2;

return A;
}


public static void main (String[] arg){
Integer max;
String Title = "Fibonacci ArryList";
String data = JOptionPane.showInputDialog(null, "Enter the upper bound", Title, 1);
max = new Integer(data);
ArrayList<Integer> A = Fibonacci(max);
System.out.println("There are " + A.size()+ " Fibonacci numbers less than "+max);

}

}

最佳答案

修改并简化了Fibonacci函数的逻辑。添加了评论以帮助您了解更改。

public static ArrayList<Integer> Fibonacci (Integer max) { //Instead of 'Max' use 'max'
ArrayList<Integer> A = new ArrayList<Integer>();

//Initialize value of n0, n1 and n2
int n0=0;
int n1=1;
int n2=1;

//Handling the base conditions
if(max == 0) return A;

if(max == 1) {
A.add(n0);
return A;
}

//Add first 2 elements in the array
A.add(n0);
A.add(n1);

//A 'while' loop will be more suitable to what you want to achieve
while(n2 < max) {
A.add(n2); //Instead of printing the values, add them into ArrayList A
n0=n1;
n1=n2;
n2 = n1 + n0;
} //Add a closing bracket for the 'for' loop

return A;
}

关于java - 使用斐波那契数列的基本数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32686209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com