计算单个文本框中数字的平均值 vb

Calculating the average of numbers in a single textbox vb

我需要获取文本框中的所有数字,然后将其转换为平均数。

我的代码:

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,因此在数字之间创建 space。

如何计算这些数字的平均值并将其放入 label1

这里的课程应该是:

  • 编程不是你“学会”的东西
  • 大多数任务由几个较小的任务组成(迭代数组、求总数、做算术)
  • 学习新东西通常需要几个 小时 的研究(数组、迭代、数据类型、索引、调试...)才能编写 10 行代码
  • MSDN 有很多补救教程,VS 甚至有视频!

计算字符串数组的平均值:

我假设文本框是代码中的 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)

如果我理解正确的话,我想你应该有以下几行:

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