' 本程序为学习而写 , 没有任何实际意义 VB.NET
Public Class Point
Private x As Single 'X Coordinate
Private y As Single 'Y Coordinate
..........................
End Class
Public Class Line
Inherits Point
Private vertexA As Point
Private vertexB As Point
Public Function SlopeOfLine() As Object
Dim slope As Single
If vertexA.propertyX = vertexB.propertyX Then
slope = False 'false stands for that this line' slope dosn't exist.
Else
slope = (vertexA.propertyY - vertexB.propertyY) / _
(vertexA.propertyX - vertexB.propertyX)
End If
Return slope
End Function
Public Function Parallel(ByVal l1 As Line) As Boolean
If Me .SlopeOfLine() = l1.SlopeOfLine() Then
Return True
Else
Return False
End If
End Function
Public Function Vertical(ByVal l1 As Line) As Boolean
If Me .Parallel(l1) Then ' parallel is true, is not vertical
Return False
'when not parallel
Else
If (Me .SlopeOfLine() = 0 And l1.SlopeOfLine() = False ) Or _
(Me .SlopeOfLine() = False And l1.SlopeOfLine() = 0) Then
Return True
ElseIf (Me .SlopeOfLine() * l1.SlopeOfLine() = -1) Then
Return True
End If
End If
End Function
End Class
求斜率的函数 ( Function SlopeOfLine() As Object ) 因为在存在一个特殊情况 , 就是直线垂直于 X 轴时 , 其斜率是不存在的 , 而在其他情况下 , 直线的斜率为一浮点型数 , 所以这个函数存在两种类型的返回值 , 于是我就把其定义为 Object 类型 , 目的就是为了处理特殊情况 .
然而在 Function SlopeOfLine() As Object 中 , 却 Dim slope As Single , 接下来 , 把特殊情况下的 slope 赋值为 FALSE, 而 FALSE 为 VB.NET 中的一关键字 , 是有特殊意义的 , 其值为 0.
这样 , 在 Function Parallel(ByVal l1 As Line) As Boolean 中 , 会把一条斜率为 0 的直线和一条没有斜率的直线认为是平行的 , 这样 , 就产生了逻辑错误
具体的改正方法是 , 把 slope 定义为 Object 型 , 并且在直线的斜率存在时 , 给其赋非关键字的值 .
Public Function SlopeOfLine() As Object
Dim slope As Object
If vertexA.propertyX = vertexB.propertyX Then
slope = noSlope ' noSlope stands for that this line' slope dosn't exist.
Else
slope = (vertexA.propertyY - vertexB.propertyY) / _
(vertexA.propertyX - vertexB.propertyX)
End If
Return slope
End Function
这样 , 就不会产生原程序中的逻辑错误了 .
---------------------------------------------------------------------------------
2008年4月9日