在Fortran中重新启动循环

efe*_*fef 3 algorithm fortran loops fortran77 fortran90

我有一个看起来像这样的算法:

10 WRITE (*,*) "Start"
DO I = 1, 10
WRITE (*,*) "Step"
IF(I .EQ. 5) then 
    go to 10
END IF
END DO
Run Code Online (Sandbox Code Playgroud)

当if语句执行时,我想重新启动循环.但是,我不想使用去,我试过这个:

10 WRITE (*,*) "Start"
DO I = 1, 10
WRITE (*,*) "Step"
IF(I .EQ. 5) then 
    I = 0; CYCLE
END IF
END DO
Run Code Online (Sandbox Code Playgroud)

但后来我得到的错误是我无法在循环内重新定义I变量.所以我不确定如何处理这个问题.任何帮助将非常感激

fra*_*lus 9

一个概念上简单的方法来表达这个问题是:"我想重复一个循环,直到它完成,哪里有一些中止条件".

这个"重复直到它完成"是惯用的具有不确定迭代的do构造:

do
  ...  ! Our actions; we exit this outer loop when we are satisfied
end do
Run Code Online (Sandbox Code Playgroud)

[这也可以用作do-while循环.]

内循环:

do
  do i=1,10
     ... ! A conditional statement which aborts the inner loop
     ... ! And some actions
  end do
  ! And once we're complete we exit the outer loop
end do
Run Code Online (Sandbox Code Playgroud)

现在只需要处理"中止内部"和"退出外部".这里cycleexit:

outer: do
  print*, 'Start'
  do i=1,10
    print*, 'Step'
    if (...) cycle outer   ! Abort the inner loop
  end do
  exit outer  ! The inner loop completed, so we're done
end do outer
Run Code Online (Sandbox Code Playgroud)

标记外部循环,以便cycle内部循环中的语句可以引用它.没有该标签,cycle将循环包含它的最内层循环.