繁体   English   中英

如何在java中计算平均值?

[英]How to calculate average in java?

我正在学习一个教程,但我没有得到我们得到这些数字平均值的部分。
请您解释一下这些数字是如何计算的以及我们如何得到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);

结果 -> 7.5

在下面找到该流正在做什么的细分

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.

所以这个解决方案对你有好处,只需要摆脱.map(n -> n * n)来计算数字的平均值而不是它们的平方。

暂无
暂无

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

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