samedi 4 février 2017

Populate an array with random numbers in the range of 0-4 with an increment of 0.5

So I have initialised an array to size 10 and trying to populate it with random numbers in the range 0.5-4 at an increment of 0.5 using a for loop. This was my initial attempt:

    double increment = 0.5;
    double[] numbers = new double[10];
    Random nextVal = new Random();
    double value = 0;

    for (int i = 0;i < numbers.length;i++){
        value = 0.5 + nextVal.nextInt(5);

        while (value == 4.5){
            value = value - increment;
        }
        numbers[i] = value;
    }

However this only adds 0.5 to the random integer values in the range instead of incrementing by 0.5.

Maybe the for loop isn't the right approach because of the differences in 'int' and 'double' variables...not totally sure. Any hints or help would be great! Thanks




Aucun commentaire:

Enregistrer un commentaire