数组中对象的错误总和计算

时间:2012-10-23 07:34:31

标签: vb.net sum

我收到了一个带有对象(我们称之为Obj)的代码,其中包含一个名为Number的属性。这些对象的数组由索引0..39中的40个对象定义。我不需要索引0处的对象。

代码有一个静态变量,用于保存数组中Number的所有Obj的总和。此变量仅初始化一次。在定义Number值本身之后。

它通常有效,但有时我会记录一个异常(我无法重现)与不同对象的值,我看到NumberAll的值是错误的(我最近记录了1722并不是说它应该重要 - 但它们唯一的共同主要因素是2.应该是1554,如果你想知道,你可以在下面查看:))。

编辑:例外情况是下面代码中的循环Index was outside the bounds of the array - 这个问题的直接影响。

我尝试过以下两种求和方法。

相关代码如下。代码中没有其他地方可以为NumberAll分配值。

Static NotFirstTime As Boolean, NumberAll As Integer

If NotFirstTime = False Then GoTo Data

sPoint:    'Code and more code
' ...
' ...
breakValue = someValue Mod NumberAll
Sum = 0
I = 1
    Try
        Do
            If Sum + myArray(I).Number >= breakValue Then
                Exit Do
            End If
            Sum = Sum + myArray(I).Number
            I = I + 1
        Loop
    Catch ex As Exception
        'log error and variable data - breakValue is larger than Sum will ever get
        'hence the loop reaches the point of trying myArray(40) which doesn't exist
    End Try

' ...

Data:
    NotFirstTime = True

    myArray(1).Number = 37
    myArray(2).Number = 34
    myArray(3).Number = 44
    myArray(4).Number = 31
    myArray(5).Number = 59
    myArray(6).Number = 26
    myArray(7).Number = 33
    myArray(8).Number = 28
    myArray(9).Number = 20
    myArray(10).Number = 13
    myArray(11).Number = 92
    myArray(12).Number = 65
    myArray(13).Number = 71
    myArray(14).Number = 22
    myArray(15).Number = 22
    myArray(16).Number = 42
    myArray(17).Number = 26
    myArray(18).Number = 26
    myArray(19).Number = 33
    myArray(20).Number = 34
    myArray(21).Number = 22
    myArray(22).Number = 19
    myArray(23).Number = 85
    myArray(24).Number = 72
    myArray(25).Number = 47
    myArray(26).Number = 40
    myArray(27).Number = 47
    myArray(28).Number = 54
    myArray(29).Number = 48
    myArray(30).Number = 44
    myArray(31).Number = 37
    myArray(32).Number = 34
    myArray(33).Number = 44
    myArray(34).Number = 9
    myArray(35).Number = 57
    myArray(36).Number = 37
    myArray(37).Number = 19
    myArray(38).Number = 13
    myArray(39).Number = 68
    NumberAll = 0

    'Only one of the following methods is used. They seem to give the same result. The bug exists in both.

    'Method one
    For I = 1 To 39 'E מספר המסכתות
        NumberAll = NumberAll + myArray(I).Number
    Next I

    'Method two
    Dim myList As List(Of Obj) = New List(Of Obj)(myArray)
    NumberAll = myList.Sum(Function(b) b.Number)
    NumberAll -= myArray(0).Number
GoTo sPoint

0 个答案:

没有答案