Julia代码中变量已经初始化定义,但后续使用报错“not defined”
技术分享
发布于 2025-01-07 14:57:13
查看 11过去511天
问题现象
运行以下代码时,命令行会报错
x = 1.5
c = 1;
d=zeros(4)
while c <= 4
d[c] = ty_round(x);
c += 1;
x += 1;
end
报错信息如下
┌ Warning: Assignment to `c` in soft scope is ambiguous because a global variable by the same name exists: `c` will be treated as a new local. Disambiguate by using `local c` to suppress this warning or `global c` to assign to the existing global variable.
└ @ Untitled-5.jl:7
┌ Warning: Assignment to `x` in soft scope is ambiguous because a global variable by the same name exists: `x` will be treated as a new local. Disambiguate by using `local x` to suppress this warning or `global x` to assign to the existing global variable.
└ @ Untitled-5.jl:8
ERROR: UndefVarError: `x` not defined
Stacktrace:
[1] top-level scope
@ .\Untitled-5.jl:6
问题原因
在 Julia 中,每个模块有自身的全局作用域/命名空间,因此同样的变量在for或者while这种循环中,需要重新定义,或者将其声明为全局变量。
解决方法
修改代码如下
x = 1.5
c = 1;
d=zeros(4)
while c <= 4
global c,x # 声明变量c、x为全局变量
d[c] = ty_round(x);
c += 1;
x += 1;
end
d的结果为
julia> d
4-element Vector{Float64}:
2.0
3.0
4.0
5.0
关于变量作用域可参阅用户手册变量作用域。
所属专栏:Julia语言
产品信息:Syslab科学计算环境