简体   繁体   English

如何在java中计算平均值?

[英]How to calculate average in java?

I'm following a tutorial and I didn't get this part where we get the average of these numbers.我正在学习一个教程,但我没有得到我们得到这些数字平均值的部分。
Would you please explain how are these numbers calculated and how do we get 7.5 as result ?请您解释一下这些数字是如何计算的以及我们如何得到7.5作为结果?

//   Finding the average of the numbers squared

    Arrays.stream(new int[] {1,2,3,4}).map(n -> n * n).average().ifPresent(System.out::println);

result -> 7.5结果 -> 7.5

Find below the breakdown of what that stream is doing在下面找到该流正在做什么的细分

Arrays.stream(new int[] {1,2,3,4}) //Converts int[] to IntStream
.map(n -> n * n) //Squares each element of the stream, now we have 1, 4, 9, 16
.average() // Calculate average between those numbers, it's 7.5
.ifPresent(System.out::println); //We have an Optional<Double>, if it's present we print it.

So this solution is good for you, just have to get rid of .map(n -> n * n) to calculate the average of the numbers and not their square.所以这个解决方案对你有好处,只需要摆脱.map(n -> n * n)来计算数字的平均值而不是它们的平方。

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

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