首页 > 解决方案 > 无法访问 Julia 数组(BoundsError:尝试访问索引 [1] 处的 0 元素 Vector{Int64})

问题描述

朱莉娅代码:

seed = 1234
N = 2
newNum = Int64[]
for i in 1:N
    seq = digits(seed*seed, pad=8)
    seed = seq[6]*1000+seq[5]*100+seq[4]*10+seq[3]
    newNum[i] = seed
end
newNum[2]

错误:https ://i.imgur.com/mn6fHwL.png

标签: arraysjulia

解决方案


采用:

seed = 1234
N = 2
newNum = Int64[]
for i in 1:N
    seq = digits(seed*seed, pad=8)
    seed = seq[6]*1000+seq[5]*100+seq[4]*10+seq[3]
    push!(newNum, seed)
end
newNum[2]

或者

seed = 1234
N = 2
newNum = Vector{Int64}(undef, N)
for i in 1:N
    seq = digits(seed*seed, pad=8)
    seed = seq[6]*1000+seq[5]*100+seq[4]*10+seq[3]
    newNum[i] = seed
end
newNum[2]

但是,一般来说,我建议您将此代码包装在一个函数中,否则效率会很低,而且如果您尝试将其作为脚本运行(即在 REPL 中不以交互方式运行),您将收到错误消息:

┌ Warning: Assignment to `seed` in soft scope is ambiguous because a global variable by the same name exists: `seed` will 
be treated as a new local. Disambiguate by using `local seed` to suppress this warning or `global seed` to assign to the existing global variable.
└ 
ERROR: LoadError: UndefVarError: seed not defined

原因是这是一个全局变量,您在循环seed引入的局部范围内重新绑定。for您可能想查看Julia 手册的这一部分以了解更多信息。


推荐阅读