继续添加前两个数字

时间:2014-03-26 23:54:57

标签: java

我写了一个包含fillFibonacciArray方法的Fibonacci类。此方法应采用单个参数,即数组。它将使用数组的前两个元素作为Fibonacci序列的前两个数字,并用序列的其余部分填充数组的其余部分。我的fillFibonacciArray方法不应该打印或返回它只是修改传递的数组作为一个参数。我不知道我是否做得对。有人可以检查一下吗?如果有什么不对请纠正我^^谢谢。!

public class Fibonacci
{

    public static void main(String[] args)
    {
        int[] fibNumbers = fillFibonacciArray(9);
        fillFibonacciArray(fibNumbers);
    }

    private static void fillFibonacciArray(int[] fibNumbers)
    {
        for (int i = 0; i < fibNumbers.length; i++)
        {

            System.out.print(fibNumbers[i]+" ");

        }
    }

    private static int[] fillFibonacciArray(int maxIndex)
    {
        int[] fibNumbers = new int[maxIndex];

        if (maxIndex > 0)
        {
            fibNumbers[0] = 1;
            if (maxIndex > 1)
            {
                fibNumbers[1] = 1;

                for (int i = 2; i < fibNumbers.length; i++)
                {
                    fibNumbers[i] = fibNumbers[i-2] + fibNumbers[i-1];
                }
            }
        }
        return fibNumbers;
    }
}

输出: 1 1 2 3 5 8 13 21 34

3 个答案:

答案 0 :(得分:1)

这符合所有规定的要求:

public class Fibonacci {

    public static void main(String[] args) {
        final int[] fibNumbers = new int[20];
        fibNumbers[0] = fibNumbers[1] = 1;

        fillFibonacciArray(fibNumbers);

        for (int i = 0; i < fibNumbers.length; i++) {
            System.out.print(fibNumbers[i] + " ");
        }
    }

    private static void fillFibonacciArray(int[] fibNumbers) {
        final int length = fibNumbers.length;

        if (length < 2) {
            throw new IllegalArgumentException("Input array must have a least 2 elements.");
        }

        for (int i = 2; i < length; i++) {
            fibNumbers[i] = fibNumbers[i - 2] + fibNumbers[i - 1];
        }

    }

}

main()的输出是:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 

答案 1 :(得分:0)

如果(maxIndex&gt; 1)更改此项 通过 if(maxIndex&gt; 2) 或者如果你的传递数组大小= 2,1或0

,你的代码中会因为i-2而发生错误

答案 2 :(得分:0)

根据OP的要求,imho应该是这样的:

import java.util.Scanner;

public class Fibonacci
{

    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        System.out.println("enter first two elements> ");
        int first = s.nextInt();
        int second = s.nextInt();

        System.out.println("define array size> ");
        int size = s.nextInt();

        if(size > 2){
            int[] fibNumbers = new int[size];
            fibNumbers[0] = first;
            fibNumbers[1] = second;
            fillFibonacciArray(fibNumbers);
        }
    }

    private static void fillFibonacciArray(int[] fibNumbers)
    {
        int maxIndex = fibNumbers.length;

         for (int i = 2; i < fibNumbers.length; i++)
         {
             fibNumbers[i] = fibNumbers[i-2] + fibNumbers[i-1];
         }

    }
}