首页 文章

计算点之间的距离

提问于
浏览
3

我正在尝试使用Scala类计算两点之间的距离 . 但它给出了一个错误说法

类型不匹配; found:other.type(带底层类型Point)必需:?{def x:?}请注意,隐式转换不适用,因为它们不明确:两个方法any2在对象Predef中设置[A]类型(x:A)确保[对象Predef中的A]和方法any2ArrowAssoc类型[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 回答

  • 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

    您也可以使用 math 模块中的内置hypot函数(如"hypotenuse"中)来计算两点之间的距离:

    case class Point(x: Double, y: Double)
    
    def distance(a: Point, b: Point): Double =
      math.hypot(a.x - b.x, a.y - b.y)
    

相关问题