vendredi 6 novembre 2015

Calculate Average of Previous Loop - Java

So, I am working on this code for my AP Computer Science class, and I ran into a problem.

First, here is my code:

//loop counters
int counterOne = 0;
int counterElse = 0;
int loop = 1;
int iNum = 1000;

//create file
PrintWriter outFile = new PrintWriter(new File("newFile.txt"));

for (int counter = 1; counter <= iNum; counter++)
    {
        while (loop >= 1)
        {
            Random rand = new Random();
            int iRand = rand.nextInt(5)+1;

            if (iRand != 1)
            {
                counterElse++;
                loop++;
            }//end of if of if-else
            else
            {
                counterOne++;
                loop = 0;
            }//end of else of if-else

        }//end of while loop

        int tries = counterElse+counterOne;
        //int average = (tries + prevTriesSum) / counter
        System.out.println("It took " + tries + " try/tries to win!");
        //outFile.println("It tool an average of " + average + " tries to win.");

    }//end of for loop

How do I calculate the average of the trials? As you can see from the end of my code, I commented out a line that I would want to calculate the average. This is because I don't know how to calculate prevTriesSum, which represents the sum of all of the other trials. Here is an example: Assume the loop runs six times, and with the first run, it takes 3 tries, 5 on the second run, 7 on the third, 11 on the fourth, 2 on the fifth, and 4 on the sixth (the most recent one. now tries = 4).

I would want prevTriesSum to equal 3 + 5 + 7 + 11 + 2 + 4.

How do I get the program to calculate that?




Aucun commentaire:

Enregistrer un commentaire