我需要将所有数字都放在文本框中,并将其转换为平均数。
我的代码:
Dim dMods1 = "\\DirectPathToSpecificFolder"
Dim dMods2 = "\\DirectPathToSpecificFolder"
Dim dMods3 = "\\DirectPathToSpecificFolder"
Dim dMods4 = "\\DirectPathToSpecificFolder"
Dim fileCount1 As Integer = Directory.GetFiles(dMods1).Length
Dim fileCount2 As Integer = Directory.GetFiles(dMods2).Length
Dim fileCount3 As Integer = Directory.GetFiles(dMods3).Length
Dim fileCount4 As Integer = Directory.GetFiles(dMods4).Length
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim array = TextBox2.Lines
TextBox2.Clear()
If Not dMods1 Is Nothing Then
For Each FilePath As String In Directory.GetFiles(dMods1, "*.txt")
TextBox2.Text &= System.IO.File.ReadAllText(FilePath) & vbNewLine
Next
For index = 0 To array.GetUpperBound(0)
Debug.WriteLine(array)
Next
End If
End Sub
现在它将附带特定文件夹中的.txt文件的内容,并将其放在textbox2中。但它会伴随vbNewLine
,因此在数字之间创造空间。
如何计算这些数字的平均值并将其放入label1
?
答案 0 :(得分:2)
如果我理解正确,我猜你应该遵循以下几点:
Dim dMods1 = "\\DirectPathToSpecificFolder"
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If Not dMods1 Is Nothing Then
For Each FilePath As String In Directory.GetFiles(dMods1, "*.txt")
TextBox2.Text &= System.IO.File.ReadAllText(FilePath) & vbNewLine
Next
Dim arrayVariable As String = TextBox2.Text
Dim sum As Integer = 0
Dim count As Integer = 0
For Each number In arrayVariable.Split(" ")
Try
sum += Convert.ToInt32(number)
count += 1
Catch
End Try
Next
Dim average As Double = sum / count
Label1.Text = Convert.ToString(average)
End If
End Sub
答案 1 :(得分:1)
这里的教训应该是:
我假设文本框是代码中的MultiLine,因此每个项目都是自己的行。
' stand in for textbox lines
Dim Lines As String() = {"1", "3", "5", "2", "8"}
' the accumulator
Dim total As Int32
Dim tmp As Int32
For n As Int32 = 0 To Lines.Count - 1
' not all text cant be converted to numbers
If Integer.TryParse(Lines(n), tmp) Then
' Lines(n) could convert to an integer
' accumulate the value
Console.WriteLine("Value at {0} is {1}", n, tmp)
total += tmp
Else
' bad news! Lines(n) cant convert!
End If
Next
' whew!
' Now the avg:
Dim intAvg = total \ Lines.Count - 1
Console.WriteLine("Integer average is {0}", intAvg)
' float/real version:
Dim fAvg = total / Lines.Count - 1
Console.WriteLine("Fractional average is {0}", fAvg)