Average within a cycle? in JAVA

0

As you can see my code what it does is generate a run of 3 random numbers, for that I use a cycle that is counting K, I am saving those numbers in an array to later add them and get the average, but it happens that I need to do it for each K, that is, when k = 1 prints 1 random result, it adds it and generates the average, and so for 2, 3, 4 until it reaches k = 30.

How could I do this? I have already tried some things and none of them has happened to me.

Code:

public static void main(String[] args) {


        double x;   //aleatoria
        double promedio=0;
        double total =0;



        for(int k=1; k<31; k++){

            x = 0+Math.random()*1;

            double arr[] = {x};

            System.out.println(x);

            for(int contador=0;contador<arr.length;contador++){
                total+=arr[contador];
            }
            promedio = total/30; 

        }

        System.out.println("El total es: "+total);
        System.out.println("El promedio es: "+ promedio);


    }

}
    
asked by Alex Palacios 12.05.2018 в 03:07
source

1 answer

0
  • Within the for , use the variable named i , it is more generic than K .
  • You do not have to save the value generated in an array, it's unnecessary.
  • You do not have to have a for within the for principal, it is also unnecessary.
  • The average can be calculated at the end, outside the% main% co.
  • In the% main% co you have for , you can simply say for .
  • You can add the values within the same%% of the main%, example: k < 31
  • As a suggestion, you can declare a constant variable at the start of the program matched to 30. With this, you will not have to change this value in each part of the code when you want more / fewer numbers generated. Example: k <= 30 . A constant is a system variable that maintains an immutable value throughout the life of the program.
  • Code with the exercise solved and improved:

    public static void main(String[] args) {
    
            double valorAleatorio; // aleatoria
            double promedio = 0;
            double total = 0;
    
            for (int i = 1; i <= 30; i++) {
    
                valorAleatorio = 0 + Math.random() * 1;
    
                System.out.println("[" + i + "] " + valorAleatorio);
    
                // Sumar valores (es lo mismo que decir: total = total + valorAleatorio)
                total += valorAleatorio;
    
            }
    
            // Promedio
            promedio = total / 30;
    
            System.out.println("El total es: " + total);
            System.out.println("El promedio es: " + promedio);
    
        }
    

    I hope I have helped you, regards!

        
    answered by 12.05.2018 / 03:27
    source