中断while循环后,变量没了赋值

我写了一个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)

输出如图:
image

可以看到,在while循环当中,lHamilrHamil还是有赋值的。但是我退出循环之后,只有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 个赞

感谢,这部分我没好好看,当python用了