简体   繁体   English

如何将数组元素的总和除以它们的数量?

[英]How can I divide the sum of my array elements with their amount?

double array_of_grades[] = new double[number_of_subjects];
double average;

for(int i=0; i < number_of_subjects; i++) {
    array_of_grades[i]=array[i].getGrade();
}

array[] is an array of objects, which contains all the information about each subject. array[]是一个对象数组,其中包含有关每个主题的所有信息。 Each subject has 1 grade. 每个科目都有1年级。 I want to get the average grade of all the subjects. 我想获得所有学科的平均成绩。

Calculate the sum: 计算总和:

double sum = 0;
for (double grade : array_of_grades) 
    sum += grade;

Then calculate the average: 然后计算平均值:

average = 1.0d * sum / array_of_grades.length;

You can use a stream from directly beginning your process from your array 您可以使用直接从array开始处理的stream

double avg = Stream.of(array)
                   .mapToDouble(x -> x.getGrade())
                   .average()
                   .getAsDouble();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM