algorithm - 在 Fortran 中重新启动循环

标签 algorithm loops fortran fortran90 fortran77

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

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/

相关文章:

java if嵌套循环

c - 将可变长度字符串分配给固定长度字符串

algorithm - 如何找到任何整数的乘法分区?

c++ - 为什么在计算多项式时霍纳斯方法没有溢出

r - 如何优化循环 R 的嵌套

asp.net - 在 typeof 上使用 instanceof 时出现 "Too much recursion"错误?

C/C++、FORTRAN、下划线和 GNU Autotools

fortran - 如何让 FORTRAN 77 读取输入?

algorithm - 鞍顶算法

string - 对 KMP 中的预处理表感到困惑