Julia Variable scope

前端 未结 1 661
南方客
南方客 2021-01-21 06:31

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 som

相关标签:
1条回答
  • 2021-01-21 07:23

    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
    

    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.

    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.

    0 讨论(0)
提交回复
热议问题