Например:
int[] numbers = {5, 8, 12, -18, -54, 84, -35, 17, 37};
Как найти среднее?
Какой алгоритм, или может есть специальные функции для этого?
Nofate♦
34.3k15 золотых знаков64 серебряных знака93 бронзовых знака
задан 17 июл 2015 в 16:55
АлександрАлександр
9736 золотых знаков13 серебряных знаков33 бронзовых знака
1
Ну например:
IntStream.of(numbers).average();
Это Java 8, stream API. Проверка: http://ideone.com/hSng8I
ответ дан 17 июл 2015 в 16:57
VladDVladD
206k27 золотых знаков289 серебряных знаков521 бронзовый знак
6
Сам алгоритм, который работает для всех версий 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;
}
ответ дан 17 июл 2015 в 21:54
1
OptionalDouble average = Arrays.stream(numbers).average();
ответ дан 17 июл 2015 в 17:36
kandikandi
5,10910 золотых знаков47 серебряных знаков96 бронзовых знаков
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);
}
}
ответ дан 22 авг 2018 в 14:10
A quick and practical guide to find and to calculate the average of numbers in array using java language.
1. Overview
In this article, you’ll learn how to calculate the average of numbers using arrays.
You should know the basic concepts of a java programming language such as Arrays and forEach loops.
We’ll see the two programs on this. The first one is to iterate the arrays using for each loop and find the average.
In the second approach, you will read array values from the user.
Let us jump into the example programs.
2. Example 1 to calculate the average using arrays
First, create an array with values and run. the for loop to find the sum of all the elements of the array.
Finally, divide the sum with the length of the array to get the average of numbers.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
Output:
3. Example 2 to find the average from user inputted numbers
Next, let us read the input array numbers from the user using the Scanner class.
Scanner Example to add two numbers
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
|
Output:
1 2 3 4 5 6 7 8 9 |
|
4. Conclusion
In this article, you’ve seen how to calculate the average number in an array.
All examples shown are in GitHub.
Average
Venkatesh Nukala is a Software Engineer working for Online Payments Industry Leading company. In my free time, I would love to spend time with family and write articles on technical blogs. More on JavaProgramTo.com
Back to top button
In this article, we will discuss how to calculate sum and average of a List or ArrayList in Java 8
- Use IntSummaryStatistics to find various parameters/statistics of a List like,
- Sum of all elements in a List using getSum() method which returns value in long-type
- Average of all elements in a List using getAverage() method which returns value in double-type
- Minimum element from a List using getMin() method which returns value in integer-type
- Maximum element from a List using getMax() method which returns value in integer-type
- Number of elements in a List (or count) using getCount() method which returns value in long-type
CalculateStatisticsOfListInJava8.java
package in.bench.resources.list.sum.average; import java.util.Arrays; import java.util.IntSummaryStatistics; import java.util.List; public class CalculateStatisticsOfListInJava8 { public static void main(String[] args) { // list List<Integer> numbers = Arrays.asList( 2, 3, 5, 7, 11, 13, 17 ); // print numbers to console System.out.println("Original elements :-"); numbers.stream().forEach(num -> System.out.println(num)); // IntSummaryStatistics using Java 8 Stream API IntSummaryStatistics statistics = numbers .stream() .mapToInt(num -> num) .summaryStatistics(); // 1. sum - print sum to the console System.out.println("n1. Sum is = " + statistics.getSum()); // 2. average - print average to the console System.out.println("n2. Average is = " + statistics.getAverage()); // 3. min - print minimum to the console System.out.println("n3. Minimum is = " + statistics.getMin()); // 4. max - print maximum to the console System.out.println("n4. Maximum is = " + statistics.getMax()); // 5. count - print count to the console System.out.println("n5. Count is = " + statistics.getCount()); } }
Output:
Original elements :- 2 3 5 7 11 13 17 1. Sum is = 58 2. Average is = 8.285714285714286 3. Minimum is = 2 4. Maximum is = 17 5. Count is = 7
2. Java – Find sum and average of a List
- In the below illustrations, we will find sum, average, minimum, maximum and count of elements in a List
- Sum – by iterating using enhanced for-loop and adding/summing & saving in a variable
- Average – divide above calculated sum by number of elements (or size of elements)
- Sort List elements in ascending order
- Minimum – get 1st element from sorted List using index 0
- Maximum – get last element from sorted List using last index i.e., (size – 1)
- Use size() method of List to get number/count of elements
CalculateStatisticsOfList.java
package in.bench.resources.list.sum.average; import java.util.Arrays; import java.util.Collections; import java.util.List; public class CalculateStatisticsOfList { public static void main(String[] args) { // local variables int sum = 0; double average = 0.0; // list List<Integer> numbers = Arrays.asList( 2, 3, 5, 7, 11, 13, 17 ); // print numbers to console System.out.println("Original elements :-"); numbers.stream().forEach(num -> System.out.println(num)); // sort List elements to find min and max Collections.sort(numbers); // find sum by iterating using enhanced for-loop for(int num : numbers) { sum += num; } // 1. sum - print sum to the console System.out.println("n1. Sum is = " + sum); // find average by dividing sum and size of List elements average = (double) sum / (double) numbers.size(); // 2. average - print average to the console System.out.println("n2. Average is = " + average); // 3. min - print minimum to the console System.out.println("n3. Minimum is = " + numbers.get(0)); // 4. max - print maximum to the console System.out.println("n4. Maximum is = " + numbers.get(numbers.size() - 1)); // 5. count - print count to the console System.out.println("n5. Count is = " + numbers.size()); } }
Output:
Original elements :- 2 3 5 7 11 13 17 1. Sum is = 58 2. Average is = 8.285714285714286 3. Minimum is = 2 4. Maximum is = 17 5. Count is = 7
Related Articles:
- Java 8 – Find Largest number in an Arrays or List or Stream
- Java 8 – Find Smallest number in an Arrays or List or Stream
- Java 8 – Find 2nd Largest number in an Arrays or List or Stream
- Java 8 – Find 2nd Smallest number in an Arrays or List or Stream
- Java 8 – Find sum of Largest 2 numbers in an Arrays or List or Stream
- Java 8 – Find sum of Smallest 2 numbers in an Arrays or List or Stream
- Java 8 – Find 1st and Last elements in an Arrays
- Java 8 – Find 1st and Last elements in a List or ArrayList
- Java 8 – Find 1st and Last elements in a Set or HashSet
- Java 8 – Find 1st and Last entries in a Map or HashMap
- Java 8 – Find sum and average of a List or ArrayList
- Java 8 – How to calculate sum and average of an Arrays ?
References:
- IntStream (Java Platform SE 8 ) (oracle.com)
- IntSummaryStatistics (Java Platform SE 8 ) (oracle.com)
Happy Coding !!
Happy Learning !!
Данная статья написана командой Vertex Academy. Это одна из статей из нашего «Самоучителя по Java.»
Условие задачи:
1. Создайте 2 массива из 5 случайных целых чисел из отрезка [0;5] каждый
2. Выведите массивы на экран в двух отдельных строках
3. Посчитайте среднее арифметическое элементов каждого массива и сообщите, для какого из массивов это значение оказалось больше (либо сообщите, что их средние арифметические равны)
Решение:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.util.Arrays; public class Test { public static void main(String[] args) { int [] mas1 = new int[5]; int [] mas2 = new int[5]; for (int i = 0; i < 5; i++) { mas1[i] = (int)(Math.random()*6); mas2[i] = (int)(Math.random()*6); } System.out.println(Arrays.toString(mas1)); System.out.println(Arrays.toString(mas2)); double average1 = 0; double average2 = 0; for (int i = 0; i < 5; i++) { average1 += mas1[i]; average2 += mas2[i]; } average1/=5; average2/=5; if(average1 > average1){ System.out.println(«Среднее арифметическое первого массива («+average1+«) больше среднего арифметического «+ «второго массива («+average2+«)»); } else if(average1 < average2){ System.out.println(«Среднее арифметическое первого массива («+average1+«) меньше среднего арифметического «+ «второго массива («+average2+«)»); } else { System.out.println(«Средние арифметические массивов равны («+average1+«)»); } } } |
Комментарии к решению:
Создаем 2 целочисленных массива на 5 элементов каждый
int [] mas1 = new int[5]; int [] mas2 = new int[5]; |
Создаем цикл, который генерирует элементы массивов. И генерируем числа в диапазоне от 0 до 5 включительно. Если подзабыли как генерируются числа в Java, прочитайте вот эту статью «Генерация случайных чисел в Java»
for (int i = 0; i < 5; i++) { mas1[i] = (int)(Math.random()*6); mas2[i] = (int)(Math.random()*6); } |
Далее выводим массивы в строку с помощью класса Arrays
System.out.println(Arrays.toString(mas1)); System.out.println(Arrays.toString(mas2)); |
Далее создаем переменные для хранения средних арифметических массивов
double average1 = 0; double average2 = 0; |
После этого находим сумму элементов массивов, а потом делим сумму на количество элементов для нахождения среднего арифметического
for (int i = 0; i < 5; i++) { average1 += mas1[i]; average2 += mas2[i]; } |
После этого сравниваем средние арифметические и выводим соответствующую фразу
if(average1 > average1){ System.out.println(«Среднее арифметическое первого массива («+average1+«) больше среднего арифметического «+ «второго массива («+average2+«)»); } else if(average1 < average2){ System.out.println(«Среднее арифметическое первого массива («+average1+«) меньше среднего арифметического «+ «второго массива («+average2+«)»); } else { System.out.println(«Средние арифметические массивов равны («+average1+«)»); } |
Найти сумму и среднее в массиве Java
1. Вступление
В этом кратком руководстве мы расскажем, как вычислить сумму и среднее значение в массиве, используя как стандартные циклы Java, так и APIStream.
2. Найти сумму элементов массива
2.1. Суммирование с использованием цикла For
Чтобы найти сумму всех элементов в массиве,we can simply iterate the array and add each element to a sum accumulating __ variable.
Это очень просто начинается сsum, равного 0, и по ходу добавления каждого элемента в массиве:
public static int findSumWithoutUsingStream(int[] array) {
int sum = 0;
for (int value : array) {
sum += value;
}
return sum;
}
2.2. Суммирование с помощью Java Stream API
Мы можем использовать Stream API для достижения того же результата:
public static int findSumUsingStream(int[] array) {
return Arrays.stream(array).sum();
}
Если мы хотим использовать поток для упакованного значенияInteger, мы должны сначала преобразовать поток вIntStream с помощью методаmapToInt.
После этого мы можем применить методsum() к нашему недавно преобразованномуIntStream:
public static int findSumUsingStream(Integer[] array) {
return Arrays.stream(array)
.mapToInt(Integer::intValue)
.sum();
}
Вы можете узнать больше о Stream APIhere.
3. Найти среднее значение в массиве Java
3.1. Среднее без Stream API
Как только мы узнаем, как вычислить сумму элементов массива, найти среднее будет довольно просто — какAverage = Sum of Elements / Number of Elements:
public static double findAverageWithoutUsingStream(int[] array) {
int sum = findSumWithoutUsingStream(array);
return (double) sum / array.length;
}
Notes:
-
Разделивint на другойint, вы получите результатint. To get an accurate average, we first cast sum to double.
-
В JavaArray есть полеlength, в котором хранится количество элементов в массиве.
3.2. Среднее значение с использованием Java Stream API
public static double findAverageUsingStream(int[] array) {
return Arrays.stream(array).average().orElse(Double.NaN);
}
IntStream.average() возвращаетOptionalDouble, которое может не содержать значения и которое требует особой обработки.
4. Заключение
В этой статье мы изучили, как найти сумму / среднее значение элементов массиваint.