Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Random Double Array from -50 to 50

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 + ','

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading