朱莉娅可变范围 [英] Julia Variable scope
问题描述
我正在尝试在while循环中使用一些全局变量(m,n,r),但是julia 1.0.0告诉我这些变量未定义.该代码适用于julia 0.7.0,并带有一些警告.
这是我正在使用的代码(是的,写得不好,我希望这不是问题.为了简单起见,我删除了println
语句):
I'm trying to use some global variables (m, n, r) in a while loop, but julia 1.0.0 is telling me that those variables aren't defined. The code works with julia 0.7.0, with some warnings.
This is the code I'm using (yes, it's poorely written, I hope this is not the problem. I removed a println
statement for the sake of simplicity):
m = readline()
n = readline()
m = parse(Int, m)
n = parse(Int, n)
r = m % n
while (r > 0)
println( "m: $(m) n: $(n) r: $(r)" )
r = m % n
m = n
n = r
end
这是茱莉亚1.0.0的结果:
This is the results with julia 1.0.0:
ERROR: LoadError: UndefVarError: m not defined
Stacktrace:
[1] top-level scope at euclide.jl:11 [inlined]
[2] top-level scope at ./none:0
[3] include at ./boot.jl:317 [inlined]
[4] include_relative(::Module, ::String) at ./loading.jl:1038
[5] include(::Module, ::String) at ./sysimg.jl:29
[6] exec_options(::Base.JLOptions) at ./client.jl:229
[7] _start() at ./client.jl:421
in expression starting at euclide.jl:10
朱莉娅0.7.0:
┌ Warning: Deprecated syntax `implicit assignment to global variable `r``.
│ Use `global r` instead.
└ @ none:0
┌ Warning: Deprecated syntax `implicit assignment to global variable `m``.
│ Use `global m` instead.
└ @ none:0
┌ Warning: Deprecated syntax `implicit assignment to global variable `n``.
│ Use `global n` instead.
└ @ none:0
该代码适用于julia 0.7.0,但为什么不适用于1.0.0版?
The code works with julia 0.7.0, but why doesn't it work with version 1.0.0 ?
推荐答案
您必须像这样在循环内声明在全局范围中定义的变量,并在循环局部范围中将分配给声明为global
:
You have to declare variables you define in global scope and assign to in loop local scope as global
inside the loop like this:
m = readline()
n = readline()
m = parse(Int, m)
n = parse(Int, n)
r = m % n
while (r > 0)
println( "m: $(m) n: $(n) r: $(r)" )
global r = m % n
global m = n
global n = r
end
您必须执行此操作的原因是while
循环引入了新的局部范围,因此,没有像m = n
这样的global
关键字分配就告诉Julia m
是while
循环内的局部变量,因此然后在println( "m: $(m) n: $(n) r: $(r)" )
行中,Julia决定m
尚未定义.
The reason you have to do it is that while
loops introduce a new local scope, so without global
keyword assignment like m = n
tells Julia that m
is a local variable inside a while
loop so then in the line println( "m: $(m) n: $(n) r: $(r)" )
Julia decides that m
is yet undefined.
另请参见 https://docs.julialang.org/zh_/latest/manual/variables-and-scoping/和
See also https://docs.julialang.org/en/latest/manual/variables-and-scoping/ and Why does this assignment inside a loop fail in Julia 0.7 and 1.0? for further explanation of the scoping rules in Julia.
这篇关于朱莉娅可变范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!