我需要计算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)
}
}
}
答案 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
}
}