我有一些数组,我想做以下数学运算:
For i As Integer = 10 To 100
TransmissionArray(i) = (maxFirstArray(i) - mintranArray(i)) / (maxSecondArray(i) - mintranArray(i))
i = i + 1
Next
问题在于有时mintranArray(i)
的值高于maxFirstArray(i)
和maxSecondArray(i)
。所以程序崩溃了。
使用Try Catch
时,该程序没有关闭,但我只获得TransmissionArray() = Nothing
。
答案 0 :(得分:1)
听起来您的TransmissionArray
未正确初始化。如果你只是Dim
,就像这样:
Dim TransmissionArray() As Double
然后它将是Nothing
。如果您尝试以这种方式为其分配值,您将获得异常。通常,您可以在括号中插入一个数字(Dim TransmissionArray(10) As Double
),并且您将拥有一个长度为10的数组,您可以立即开始为其赋值。但是,如果您事先不知道长度,我可以考虑两个可行的选项:
Dim TransmissionArray() As Double
For i As Integer = 10 To 100
ReDim Preserve TransmissionArray(i) 'This will increase the size of the array to the value of i, the Preserve keyword also saves the data already stored in the array
TransmissionArray(i) = (maxFirstArray(i) - mintranArray(i)) / (maxSecondArray(i) - mintranArray(i))
'i = i + 1 'Commented this out...i is already incremented once each loop
Next
或者,切换为使用List(Of Double)
:
Dim TransmissionArray As New List(Of Double)
For i As Integer = 10 To 100
TransmissionArray.Add((maxFirstArray(i) - mintranArray(i)) / (maxSecondArray(i) - mintranArray(i)))
'i = i + 1 'Commented this out...i is already incremented once each loop
Next
请注意,第二种方法会使TransmissionArray
项比其他数组少10项,因为您在10处启动For
循环计数器,只是将项添加到列表中。 / p>