Home > Software design >  Java Random Double Array from -50 to 50
Java Random Double Array from -50 to 50

Time:11-17

I need to populate an array with random numbers from -50 to 50 and need to use Math.random(). Here is my current code:

double[] randomNums = new double[5];

for (int i = 0; i < randomNums.length; i  ) {
    randomNums[i] = 100 * Math.random() - 50;
}
for (double i: randomNums) {
    System.out.println(i   ',');
}

Output:

-5.836717454677796,
44.07635593282988,
23.650145270722884,
93.00810678750743,
54.0536237451922

Why is this going above 50?

CodePudding user response:

You are adding the value of the char ,, which has value 44 to each double. You can test this using:

System.out.println(0   ',');

Output: 44

To fix this you can simply remove the ','

  • Related