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?
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?
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; }
Well, for example :
IntStream.of(numbers).average();
This is Java 8, stream API. Check: http://ideone.com/hSng8I
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); } }
Source: https://ru.stackoverflow.com/questions/436370/
All Articles