如何终止do循环?

时间:2015-12-07 13:39:05

标签: loops fortran gfortran

我正在编写一个非常基本的Fortran代码来创建Ising模型。但是,我被困在最后一步 - 重复计算直到达到最稳定的状态。

do
!Calculation (omitted here)
!Making a decision
if (E1 /= -64) then             !not yet stable
    if(dE > 0.0) then       
    call seed
    call random_number(prob)        ! random generate a number which is 0 <= Prob <= 1      
    Print *, prob
        if(Prob < exp(-dE/T)) then
                        !do nothing as the flip was made
        else
        mat(b,c) = -mat(b,c)        !flip the sign back, i.e. reject the change; only accept with probability of exp(-dE/T)
        end if
    else
    end if                  !Since the sign has changed already, if dE<0, the move must be accepted. Therefore no additional move should be taken
else
end do
end if
end do

显然,Fortran不喜欢第二个end do语句,因为我没有特别定义do。我想要的只是do循环E1 == -64循环。

2 个答案:

答案 0 :(得分:5)

在Fortran中,您可以使用exit语句随时退出do循环。

  do
    ...
    if (condition) exit
  end do

如果标记了do循环,请使用exit语句中的标签

outer: do
  inner: do
    ...
    if (condition) exit outer
  end do inner
end do outer

Fortran 2008也允许退出语句用于其他构造。

答案 1 :(得分:0)

你应该可以使用while循环。

while (E1 [.ne. OR /=] -64) do
   [your code]
end do

这需要在循环内更新E1。如果没有此更新,E1将始终不等于-64并导致无限循环。您的代码并未明确显示此情况。我认为确实如此,但要记住这一点。