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

Tutoriel de base Java

Contrôle de flux Java

Java tableau

Java orienté objet (I)

Java orienté objet (II)

Java orienté objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map collectif

Java Set collectif

Entrées et sorties Java (I/O)

Java Reader/Writer

Autres sujets Java

Programme Java pour calculer la moyenne en utilisant un tableau

Java complete list of examples

Dans ce programme, vous apprendrez à calculer la moyenne d'un tableau donné en Java.

Exemple : programme pour calculer la moyenne d'un tableau

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 complete list of examples