English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Básico de Java

Java Controle de Fluxo

Java Array

Java Orientação a Objetos (I)

Java Orientação a Objetos (II)

Java Orientação a Objetos (III)

Tratamento de Exceções Java

Java Lista (List)

Java Fila (Queue)

Java Mapa (Map)

Java Conjunto (Set)

Java Entrada e Saída (I/O)

Java Reader/Writer

Outros tópicos do Java

Programa Java para calcular a média de um array

Java Examples

Neste programa, você aprenderá a calcular a média de um array em Java.

Exemplo: programa para calcular a média de um array

public class Average {
    public static void main(String[] args) {
        double[] numArray = { 45.3, 67.5, -45.6, 20.34, 33.0, 45.6 };
        double sum = 0.0;
        for (double num: numArray) {
           sum += num;
        }
        double average = sum / numArray.length;
        System.out.format("The average is: %.2f", average);
    }
}

When running the program, the output is:

The average is: 27.69

In the above program, numArray stores the floating-point values required for the average.

Then, to calculate average, we need to first calculate the sum of all elements in the array. This is done using Java's for-the loop is completed.

Finally, we calculate the average using the following formula:

average = total sum of numbers / Total number of array elements (numArray.length)

In this case, the total number of elements is given by numArray.length.

Finally, we use the format() function to print the average so that we can use "%.2f"

Java Examples