/** * 已知三点坐标,求其中一点到另两点的垂线距离 * (如果在垂足不在线段内,最短距离为到其中一点的直线距离) * Created by wzq on 17-11-2. */object Point2lineDistance { def main(args: Array[String]) { val v: Double = pointToLine(-3, 0, 3, 0, 0, 3) System.out.println(v) } def pointToLine(x1: Int, y1: Int, x2: Int, y2: Int, x0: Int, y0: Int): Double = { var space: Double = 0 var a: Double = .0 var b: Double = .0 var c: Double = .0 a = lineSpace(x1, y1, x2, y2) // 线段的长度 b = lineSpace(x1, y1, x0, y0) // (x1,y1)到点的距离 c = lineSpace(x2, y2, x0, y0) // (x2,y2)到点的距离 if (c <= 0.000001 || b <= 0.000001) { space = 0 return space } if (a <= 0.000001) { space = b return space } //钝角三角形的最小边长 if (c * c >= a * a + b * b) { space = b return space } if (b * b >= a * a + c * c) { space = c return space } val p: Double = (a + b + c) / 2 // 半周长 val s: Double = Math.sqrt(p * (p - a) * (p - b) * (p - c)) // 海伦公式求面积 space = 2 * s / a // 返回点到线的距离(利用三角形面积公式求高) space } // 计算两点之间的距离 private def lineSpace(x1: Int, y1: Int, x2: Int, y2: Int): Double = { var lineLength: Double = 0 lineLength = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) lineLength }}
时间: 2024-10-24 11:51:06