我写了一个while
循环:
lbound = ubound = zWithMaximumHamiltonian
i = 0
rHamil = getHamiltonian(ubound)
while i < 300
lHamil = rHamil
rHamil = getHamiltonian(ubound+(i+1)*Δz)
if (lHamil > refHamil) && (rHamil <= refHamil)
lbound = ubound+i*Δz
ubound = ubound+(i+1)*Δz
println(lHamil, " ", rHamil)
break
end
i += 1
end
println(rHamil)
println(lHamil)
输出如图:
可以看到,在while
循环当中,lHamil
和rHamil
还是有赋值的。但是我退出循环之后,只有lHamil
丢了,这是怎么回事呢?
在while内定义的变量是局域的,而while外定义的是全局的。
所以你可以在循环前对lHamil
赋初值来使其变为全局变量。
lbound = ubound = zWithMaximumHamiltonian
i = 0
rHamil = getHamiltonian(ubound)
lHamil = rHamil # 添加这一句
while i < 300
lHamil = rHamil
rHamil = getHamiltonian(ubound+(i+1)*Δz)
if (lHamil > refHamil) && (rHamil <= refHamil)
lbound = ubound+i*Δz
ubound = ubound+(i+1)*Δz
println(lHamil, " ", rHamil)
break
end
i += 1
end
println(rHamil)
println(lHamil)
更详细的参见文档中作用域的相关部分https://docs.juliacn.com/v1.2/manual/variables-and-scoping/
1 个赞