0

好吧,我很难弄清楚我做错了什么。基本上我需要删除比平均数少的 Listbox1 项目,但它给了我:

System.ArgumentOutOfRangeException 未处理 Message=InvalidArgument='9' 的值对'index' 无效。参数名称:索引

Private Sub Label3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label3.Click
    Dim Myrand As New Random
    Dim res As Double
    Dim i As Integer
    Dim n As Integer
    Dim tot As Double
    Dim avarage As Double

    ListBox1.Items.Clear()

    For i = 0 To 14 Step 1
        res = Math.Round(Myrand.NextDouble, 3)
        ListBox1.Items.Add(res)
        tot = tot + res
    Next

    avarage = tot / ListBox1.Items.Count
    MsgBox(avarage)

    For i = 0 To ListBox1.Items.Count - 1 Step 1
        If ListBox1.Items(i) < avarage Then
            ListBox1.Items.RemoveAt(i)
            n = n + 1
        End If
    Next

    MsgBox("Removed " & n & " items!")
End Sub

有什么建议么?

4

2 回答 2

1

当您删除一个项目时,它不再在列表中,因此列表变得更短,并且您的原始计数不再有效。只是减少i

Private Sub Label3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label3.Click
    Dim Myrand As New Random
    Dim res As Double
    Dim i As Integer
    Dim n As Integer
    Dim tot As Double
    Dim avarage As Double

    ListBox1.Items.Clear()

    For i = 0 To 14
        res = Math.Round(Myrand.NextDouble, 3)
        ListBox1.Items.Add(res)
        tot += res
    Next

    avarage = tot / ListBox1.Items.Count
    MsgBox(avarage)

    For i = 0 To ListBox1.Items.Count - 1
        If ListBox1.Items(i) < avarage Then
            ListBox1.Items.RemoveAt(i)
            i -= 1
            n += 1
        End If
    Next

    MsgBox("Removed " & n & " items!")
End Sub
于 2012-04-29T21:52:51.457 回答
1

它在 For/Next 循环开始时获取最大计数并且不重新评估它。尝试向后迭代,这样你就可以从你没有从你要去的地方移除。

IE

For i = ListBox1.Items.Count - 1 To 0 Step -1
    If ListBox1.Items(i) < avarage Then
        ListBox1.Items.RemoveAt(i)
        n = n + 1
    End If
Next

从上面的 MSDN Link 强调我的:

当 For...Next 循环开始时,Visual Basic 计算 start、end 和 step。这是它唯一一次评估这些值。然后它将开始分配给计数器。在运行语句块之前,它将计数器与结束进行比较。如果 counter 已经大于结束值(或者如果 step 为负则更小),则 For 循环结束并且控制传递到 Next 语句之后的语句。否则语句块运行。

于 2012-04-29T22:03:30.370 回答