我正在尝试编写一种方法来计算ListScala中给定元素的平均值。这是我的代码:
def meanElements(list: List[Float]): Float = {
list match {
case x :: tail => (x + meanElements(tail))/(list.length)
case Nil => 0
}
}
Run Code Online (Sandbox Code Playgroud)
当我打电话时meanElements(List(10,12,14))),我得到的结果与 12 不同。有人可以帮忙吗?
您可以使用内置函数简单地做到这一点:
scala> def mean(list:List[Int]):Int =
| if(list.isEmpty) 0 else list.sum/list.size
mean: (list: List[Int])Int
scala> mean(List(10,12,14))
res1: Int = 12
scala>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5275 次 |
| 最近记录: |