计算点之间的距离

时间:2014-10-04 01:44:24

标签: scala

我试图使用Scala类计算两点之间的距离。但它给出了一个错误说

  

类型不匹配;发现:other.type(底层类型为Point)   required:?{def x:?}请注意,隐式转换不是   适用,因为它们不明确:两种方法any2Ensuring in   object [A]类型的Predef(x:A)确保[A]和方法any2ArrowAssoc   in对象Predef类型[A](x:A)ArrowAssoc [A]是可能的   转换函数从other.type转换为?{def x:?}

class Point(x: Double, y: Double) {
  override def toString = "(" + x + "," + y + ")"


  def distance(other: Point): Double = {
    sqrt((this.x - other.x)^2 + (this.y-other.y)^2 )
  }
}

2 个答案:

答案 0 :(得分:4)

以下编辑非常适合我:

import math.{ sqrt, pow }

class Point(val x: Double, val y: Double) {
  override def toString = s"($x,$y)"

  def distance(other: Point): Double =
    sqrt(pow(x - other.x, 2) + pow(y - other.y, 2))
}

我还想指出,Point作为案例类更有意义:

case class Point(x: Double, y: Double) { // `val` not needed
  def distance(other: Point): Double =
    sqrt(pow(x - other.x, 2) + pow(y - other.y, 2))
}

val pt1 = Point(1.1, 2.2) // no 'new' needed
println(pt1)  // prints Point(1.1,2,2); toString is auto-generated
val pt2 = Point(1.1, 2.2)
println(pt1 == pt2) // == comes free
pt1.copy(y = 9.9) // returns a new and altered copy of pt1 without modifying pt1

答案 1 :(得分:1)

您也可以使用math模块中的内置enter image description here函数(如“斜边” )来计算两点之间的距离:

case class Point(x: Double, y: Double)

def distance(a: Point, b: Point): Double =
  math.hypot(a.x - b.x, a.y - b.y)
相关问题