我正在尝试在while循环中使用一些全局变量(m,n,r),但是julia 1.0.0告诉我这些变量未定义。该代码适用于julia 0.7.0,并带有一些警告。
这是我正在使用的代码(是的,写得不好,我希望这不是问题。为了简单起见,我删除了println
语句):
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的结果:
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版?
答案 0 :(得分:3)
您必须声明在全局范围内定义的变量,并在循环本地范围内将{em> assign to 分配为global
,如下所示:
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
循环引入了新的本地范围,因此如果没有像global
这样的m = n
关键字分配,便会告诉Julia m
是本地的while
循环中的变量,因此在println( "m: $(m) n: $(n) r: $(r)" )
行中,Julia决定m
尚未定义。
另请参见https://docs.julialang.org/en/latest/manual/variables-and-scoping/和Why does this assignment inside a loop fail in Julia 0.7 and 1.0?,以了解Julia的范围规则。
答案 1 :(得分:0)
您实际上是否已经按照警告消息那样在代码模块顶部声明了变量?
global r
global m
global n
欢迎来到Stackoverflow!