Home > OS >  Assign random doubles in arrays and claculate the average
Assign random doubles in arrays and claculate the average

Time:12-04

I am trying to fit random numbers into an array , so that I can calculate their averages.

for(int i =0; i<4; i ){

double randomDouble = Math.random() * 100;

System.out.format("Random Number in Java: %.2f\n", randomDouble)}

I want the number to be between 1-100 and also with only one/two decimal places, so I used the above method. Now I want to Calculate average of the generated random numbers.

CodePudding user response:

You have to start by putting the values you're generating in the for-loop into an array:

arr[i] = randomDouble

Then, you could loop over the array again to get the values at each index and calculate the average, but that would waste time (you already go through the array once).

Instead, in your first loop, you can keep track of the sum of the values and return the average of that at the end:

float sum_of_array_elements = 0;

for(int i =0; i<4; i  ){ ...

...}

return sum_of_array_elements/4;

CodePudding user response:

Use:

int v = ThreadLocalRandom.current().nextInt(1,101);

The 1 is an inclusive lower bound. The 101 is an exclusive upper bound.

If you want decimal points then use:

nextDouble(1,101);

see: https://www.baeldung.com/java-thread-local-random

  • Related