计算Scala平均值

时间:2017-11-15 21:52:45

标签: scala average

我需要计算Scala中三个年龄段的平均值。我尝试过下面显示的方法,但它没有用。请帮忙。

sealed abstract class Component
case class Life (age:Int) extends Component

object Life extends Component{
  def main(args: Array[String]){
    val lives = List{Life(10), Life(20), Life(30)}
    def livesMean (l:List[Life]):Double = {
        println(livesMean)
    }
  }
}

2 个答案:

答案 0 :(得分:1)

首先,您已经错误地声明了生命对象列表。并找到平均值,取出年龄之和并将其除以列表大小。

sealed abstract class Component
case class Life (age:Int) extends Component

object Main extends Component{
    def main(args: Array[String]){
    val lives = List(Life(10), Life(20), Life(30))
    def livesMean (l:List[Life]):Double = lives.map(_.age).sum/lives.size
    println("average of lives "+ livesMean(lives))
  }
}

正在运行。你可以看到它here

答案 1 :(得分:0)

您用于创建lives的语法无效。这应该有效:

abstract class Component

case class Life(age: Int) extends Component

object Life extends Component {
    def main(args: Array[String]) {
        val lives = List(new Life(10), new Life(20), new Life(30))
        val livesMean: Double = lives.map(_.age).sum / lives.size
        println(livesMean) // 20.0
    }
}

斯卡拉小提琴:https://scalafiddle.io/sf/Lyu9VRf/0