arrays - 无法访问 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]
解决方案
采用:
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 手册的这一部分以了解更多信息。
推荐阅读
- css - 如何防止具有相对位置的组件不会出现在带有角度粘性标题的表格上方?
- python-3.x - 击键记录:记录按下和释放
- node.js - 注册后无法重定向到仪表板(秘密页面)
- reactjs - 当我们声明一个 const 并重用变量时
- sql - 用前导零修剪特定字符串
- c# - 如何从模型的 ViewModel 类型的回发中从 DropdownList 中获取价值?
- lua - 我的游戏没有保存我希望它保存的数据
- authentication - 如何在 actix-web 中创建受保护的路由
- typescript - TypeScript 类型限制有时不适用
- autodesk-forge - Autodesk 查看器 setZoomOutLimitFactor(因子)不起作用