This is a Java problem I am having, I am somewhat new to Java.
I have to:
-
generate a random fraction
-
keep generating until the sum is greater than 1
-
then I have to display how many numbers I generated and which ones
Here is what I have so far in my function:
public static double calcAvg(int numOfTimes){
double sumOfRand = 0 ;
int numOffractions = 0;
double avg = 0;
double numOfAvg[] = new double[numOfTimes]; // number of rows
double randNums[] = new double[] {.1,.2,.3,.4,.5,.6,.7,.8,.9};
Random rand = new Random();
for(int i = 0; sumOfRand <= 1; i++){
int randNum = rand.nextInt(randNums.length); //gets a number from array randomly
//System.out.println(randNums[randNum]);
sumOfRand += randNums[randNum]; //adds it to the sum
numOffractions++; //counts # of avgnums needed for > 1
numOfAvg[i] = numOffractions;
}
avg = (numOfAvg[0] + numOfAvg[1] + numOfAvg[2]) /(numOfTimes);
return avg;
}
I keep getting an error on: numOfAvg[i] = numOffractions;
and I can't seem to add the fractions to the sum until they pass 1.
Aucun commentaire:
Enregistrer un commentaire