我通过使用“Math.Sqrt”函数得到一条线的长度,它是X,Y坐标。因此,从文本文件中读取此坐标,并且可以出现多行的坐标,这意味着该函数将计算每行的长度。以下是代码的外观:
Dim Perimeter As List(Of Line)= LineParsing(fp)
For Each Line As Line In Perimeter
Dim x1 As Single = Line.Start.X
Dim y1 As Single = Line.Start.Y
Dim x2 As Single = Line.End.X
Dim y2 As Single = Line.End.Y
Dim Pq As Double
Pq = (Math.Sqrt(((x2 - x1) * (x2 - x1)) + (y2 - y1) * (y2 - y1)))
'Using textbox to see the output.
TextBox4.AppendText("Line Length: " & Pq & Environment.NewLine)
Next
输出:
现在我想要实现的结果就是总结这些线的长度,这将给我一个表格的周长。
任何想法我怎样才能做到这一点?提前致谢!
答案 0 :(得分:0)
您可以将长度计算合并到Line
结构/类中。这样,您每次要使用它时都不必重新键入计算。并且在每次计算之后,只需将其添加到包含总计的变量。
额外的好处是,如果你想改变计算,你只需要在一个地方改变它。
Structure Line
Friend Start As Point
Friend [End] As Point
Friend ReadOnly Property Length As Double
Get
Dim x1 As Single = Start.X
Dim y1 As Single = Start.Y
Dim x2 As Single = [End].X
Dim y2 As Single = [End].Y
Return Math.Sqrt((x2 - x1) ^ 2 + (y2 - y1) ^ 2)
End Get
End Property
End Structure
示例代码
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim perimiter As New List(Of Line)
perimiter.Add(New Line With {.Start = New Point(0, 0), .End = New Point(3, 4)})
perimiter.Add(New Line With {.Start = New Point(3, 4), .End = New Point(8, 2)})
perimiter.Add(New Line With {.Start = New Point(8, 2), .End = New Point(6, 1)})
perimiter.Add(New Line With {.Start = New Point(6, 1), .End = New Point(0, 0)})
Dim totalLength As Double = 0
For Each line As Line In perimiter
TextBox4.AppendText("Line Length: " & line.Length & Environment.NewLine)
totalLength += line.Length
Next
End Sub