用vb写某一点到线段的最短距离
时间: 2023-10-15 15:02:11 浏览: 38
以下是使用 VB.NET 实现计算点 P 到线段 AB 的最短距离的代码:
```vb
Imports System.Math
Module Module1
Structure Point
Dim x As Double
Dim y As Double
End Structure
' 计算两点间距离
Function CalcDistance(ByVal a As Point, ByVal b As Point) As Double
Return Sqrt((a.x - b.x) ^ 2 + (a.y - b.y) ^ 2)
End Function
' 计算点 P 到直线 AB 的垂足点 H
Function CalcPerpendicular(ByVal p As Point, ByVal a As Point, ByVal b As Point) As Point
Dim k As Double = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / (CalcDistance(a, b) ^ 2)
Dim hx As Double = a.x + k * (b.x - a.x)
Dim hy As Double = a.y + k * (b.y - a.y)
Return New Point With {.x = hx, .y = hy}
End Function
' 判断垂足点 H 是否在线段 AB 上
Function IsOnSegment(ByVal h As Point, ByVal a As Point, ByVal b As Point) As Boolean
Return Min(a.x, b.x) <= h.x AndAlso h.x <= Max(a.x, b.x) AndAlso Min(a.y, b.y) <= h.y AndAlso h.y <= Max(a.y, b.y)
End Function
' 计算点 P 到线段 AB 的最短距离
Function CalcShortestDistance(ByVal p As Point, ByVal a As Point, ByVal b As Point) As Double
Dim h As Point = CalcPerpendicular(p, a, b)
If IsOnSegment(h, a, b) Then
Return CalcDistance(p, h)
Else
Return Min(CalcDistance(p, a), CalcDistance(p, b))
End If
End Function
Sub Main()
Dim p As New Point With {.x = 1, .y = 1}
Dim a As New Point With {.x = 0, .y = 0}
Dim b As New Point With {.x = 2, .y = 0}
Console.WriteLine(CalcShortestDistance(p, a, b)) ' 输出 1
Console.ReadKey()
End Sub
End Module
```
以上代码中,假设点 P 为 (1,1),线段的两端点分别为 A(0,0) 和 B(2,0),输出结果为 1,表示点 P 到线段 AB 的最短距离为 1。