簡體   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