For example:

int[] numbers = {5, 8, 12, -18, -54, 84, -35, 17, 37}; 

How to find the mean? What algorithm, or maybe there are special functions for this?

  • Here it would be useful to make an FAQ out of this question. - Vesper

4 answers 4

The algorithm itself, which works for all versions of Java:

 // среднее арифметическое - сумма всех чисел деленная на их количество int[] numbers = {5, 8, 12, -18, -54, 84, -35, 17, 37}; double average = 0; if (numbers.length > 0) { double sum = 0; for (int j = 0; j < numbers.length; j++) { sum += numbers[j]; } average = sum / numbers.length; } 
  • Added fix - pavelip pm

Well, for example :

 IntStream.of(numbers).average(); 

This is Java 8, stream API. Check: http://ideone.com/hSng8I

  • one
    Feel the power of LINQ! - VladD
  • Java was asked to - kandi
  • @danpetruk: What's this? ideone.com/hSng8I - VladD pm
  • one
    @danpetruk: On C # it looks somewhat simpler: ideone.com/IoowuC , because the array is the stream itself. - VladD 5:41 pm
  • Hm Why then "Feel the power of LINQ!"? LINQ is C #. So I thought the code is sichearous - kandi
 OptionalDouble average = Arrays.stream(numbers).average(); 
     class average { public static void main(String args[]) { int num [] = {5, 8, 12, -18, -54, 84, -35, 17, 37}; double sum = 0; for (int x: num) { sum += x; } System.out.print("среднее арифметическое чисел равно: " + sum/num.length); } }