我有一个看起来像这样的算法:
10 WRITE (*,*) "Start"
DO I = 1, 10
WRITE (*,*) "Step"
IF(I .EQ. 5) then
go to 10
END IF
END DO
我想在 if 语句执行时重新启动循环。但是,我不想使用 go to,我试过这个:
10 WRITE (*,*) "Start"
DO I = 1, 10
WRITE (*,*) "Step"
IF(I .EQ. 5) then
I = 0; CYCLE
END IF
END DO
但随后我收到无法在循环内重新定义 I 变量的错误。所以我不确定如何处理这个问题。任何帮助将不胜感激
最佳答案
表达这个问题的概念上简单的方法是:“我想重复一个循环直到它完成,其中有一些中止条件”。
这种“重复直到完成”惯用的是具有不确定迭代的 do 结构:
do
... ! Our actions; we exit this outer loop when we are satisfied
end do
[这也可以表述为一个 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
现在只需要处理“abort inner”和“exit outer”。这里循环
和退出
:
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
外层循环被标记,以便内层循环中的cycle
语句可以引用它。如果没有该标签,cycle
将循环包含它的最内层循环。
关于algorithm - 在 Fortran 中重新启动循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42026668/