【问题标题】:How to calculate average in java? [closed]如何在java中计算平均值? [关闭]
【发布时间】:2021-07-30 07:55:33
【问题描述】:

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

【问题讨论】:

  • 请注意,它是每个值的平方的平均值,因为它正在执行.map(n -> n * n)map() 返回 {1,4,9,16} 并且这些值的平均值是 7.5
  • 您正在对数字进行平方,然后计算平方和的平均值。只需删除 map 语句,它就会起作用。 Arrays.stream(new int[] { 1, 2, 3, 4 }).average()
  • 你得到了什么
  • @JustAnotherDeveloper 谢谢。我现在得到了答案。

标签: java lambda stream


【解决方案1】:

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

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 -&gt; n * n) 来计算数字的平均值而不是它们的平方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-22
    • 2016-07-24
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多