English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java complete list of examples
Dans ce programme, vous apprendrez à calculer la moyenne d'un tableau donné en Java.
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"