循环更改变量[Julia] [英] Changing variable in loop [Julia]
问题描述
在Julia 1.0中,我试图沿着以下方式实现一个for循环:
In Julia 1.0, I'm trying to implement a for loop along the lines of:
while t1 < 2*tmax
tcol = rand()
t1 = t0 + tcol
t0 = t1
println(t0)
end
但是,我得到的错误是t1和t0未定义.如果我在它们前面放一个"global",它将再次起作用.是否有比通过在我的代码中放置全局变量更好的方法来解决此问题?
However, I am getting errors that t1 and t0 are undefined. If I put a "global" in front of them, it works again. Is there a better way to handle this than by putting global variables all over my code?
推荐答案
问题的原因是您正在全局范围内运行代码(可能是在Julia REPL中运行).在这种情况下,您将必须使用global
,如此处所述. https://docs.julialang.org/en/latest/manual/variables-and-scoping/.
The reason of the problem is that you are running your code in global scope (probably in Julia REPL). In this case you will have to use global
as is explained here https://docs.julialang.org/en/latest/manual/variables-and-scoping/.
我推荐的最简单的方法是将您的代码包装在let
块中,如下所示:
The simplest thing I can recommend is to wrap your code in let
block like this:
let t1=0.0, t0=0.0, tmax=2.0
while t1 < 2*tmax
tcol = rand()
t1 = t0 + tcol
t0 = t1
println(t0)
end
t0, t1
end
通过这种方式let
创建一个本地范围,并且如果您在全局范围内运行此块(例如在Julia REPL中),则一切正常.请注意,我将t0, t1
放在最后,使let
块返回一个包含t0
和t1
This way let
creates a local scope and if you run this block in global scope (e.g. in Julia REPL) all works OK. Note that I put t0, t1
at the end to make the let
block return a tuple containing values of t0
and t1
您还可以将代码包装在一个函数中:
You could also wrap your code inside a function:
function myfun(t1, t0, tmax)
while t1 < 2*tmax
tcol = rand()
t1 = t0 + tcol
t0 = t1
println(t0)
end
t0, t1
end
,然后使用适当的参数调用myfun
以获得相同的结果.
and then call myfun
with appropriate parameters to get the same result.
这篇关于循环更改变量[Julia]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!