gpt4 book ai didi

excel - 运行时错误 '9' : subscript out of range when generating an array

转载 作者:行者123 更新时间:2023-12-02 10:34:23 25 4
gpt4 key购买 nike

我正在尝试为 GA 生成种群。我使用二维数组来帮助生成种群。首先,用户将在用户表单中输入种群大小,然后输入染色体长度。

我的变量:

Dim Generation As Integer
Dim Chromolength As Integer
Dim varchromolength As Integer
Dim Poparr() As Integer

然后我从 UserForm 中获取值:

PopSize = PopulationSize.value
aVariables = AOV.value 'assign userform value entered to this variable
varchromolength = Chromolengthentered.value 'assign userform value entered to this variable
Chromolength = varchromolength * aVariables 'Chromosome length equals the length of each varaible chromosome combined

发生错误的编码:

For i = 1 To PopSize           
For j = 1 To Chromolength
If Rnd < 0.5 Then
Poparr(i, j) = 0 'assign o to gene
Else
Poparr(i, j) = 1 'assign 1 to gene
End If
Next j
Next i

最佳答案

根据您的代码,您从未分配数组的维度。为此,请在设置 PopSizeChromoLength 的值后,在 for 循环之前插入此行。

Redim Poparr(1 to PopSize, 1 to ChromoLength)

不必要的细节:您可以只运行Redim Poparr(PopSize, ChromoLength),但这会导致数组0到Popsize等...除非您将Option Base 1 添加到模块的顶部。数组的默认基数是 0。我认为最好明确指示数组的下限和上限,因为默认值可以是 0 或 1,具体取决于上下文。

关于excel - 运行时错误 '9' : subscript out of range when generating an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12585914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com