从数字范围创建数组

时间:2017-01-01 15:57:39

标签: java

我需要创建一个给定max和min和interval的双精度数组。所以数组看起来像{2.9,4.9,6.9,......等}

我得到一个零数组。

public class FoolinAround {
    public static void main(String[] args) {
        double min = 2.9;
        double max = 20.6;
        double gap = 2.0;
        double count = (max - min) / gap + 2; // as will need first and last
                                                // element also

        double array[] = new double[(int) count];
        for (int j = 0; j < array.length; j++) {
            double i = array[j];
            min = min + gap;

        }
        for (double k : array) {
            System.out.print(array[(int) k] + ",");
        }

    }
}

3 个答案:

答案 0 :(得分:1)

您似乎错过了对阵列的分配(array[j] = something;)。从你的解释看来,array应该包含结果。如果我理解您要解决的问题,这看起来像是一个解决方案。

public class FoolinAround {
    public static void main(String[] args) {
        double min = 2.9;
        double max = 20.6;
        double gap = 2.5;
        double count = (max - min) / gap + 2; // as will need first and last
                                                // element also

        double array[] = new double[(int) count];
        for (int j = 0; j < array.length; j++) {
            array[j] = min + (j*gap);
        }
        for (double k : array) {
            System.out.print(array[(int) k] + ",");
        }

    }
}

我没有验证此计算是否会为您的数组提供正确的大小:double count = (max - min) / gap + 2;。我建议你验证这个计算。由于您依赖于截断而不是舍入,因此可能会出现一个错误。

答案 1 :(得分:1)

以下是

double[] array = DoubleStream.iterate(min, prev -> prev + gap)
                             .limit(count)
                             .toArray();

Link to DoubleStream

答案 2 :(得分:0)

我发现的问题是赋值和for-each循环。以下是如何做到这一点:

    double min = 2.9;
    double max = 20.6;
    double gap = 2.0;
    double count = (max - min) / gap + 2.0;

    System.out.println(count);
    double array[] = new double[(int) count];
    for (int j = 0; j < array.length; j++) {

        // double i = array[j]; /*Not sure why this assignment is used
        // here?*/
        array[j] = min;
        min += gap;

    }

    for (double k : array) {
        System.out.print(k + "\n"); // Here k is the double value from the
                                    // array. array[(int)k] will give you
                                    // element of array indexed at the
                                    // element of array.
    }