fortran - 我们真的可以在所有情况下都避免 goto 吗?

标签 fortran fortran90 goto

Fortran 90 及更高版本强烈建议不要使用 goto 语句。

但是,我仍然觉得在这两种情况下不得不使用它:

情况1 -- 指示重新输入输入值,例如

      program reenter   
10    print*,'Enter a positive number'
      read*, n

      if (n < 0) then
      print*,'The number is negative!'
      goto 10
      end if

      print*,'Root of the given number',sqrt(float(n))

      stop
      end program reenter

情况 2 -- 注释程序的大部分连续部分(相当于 C 中的 /* ... */)。 例如。

       print*,'This is to printed'
       goto 50
       print*,'Blah'
       print*,'Blah Blah'
       print*,'Blah Blah Blah'   
 50    continue
       print*,'Blahs not printed'

在 Fortran 90 中,如何摆脱使用 goto 语句并在上述两种情况下使用一些替代方案?

最佳答案

案例1

你所拥有的是一个无限循环,循环直到满足条件。

do
  read *, n
  if (n.ge.0) exit
  print *, 'The number is negative!'
end do
! Here n is not negative.

或者可以使用 do while block 。

<小时/>

案例2

非 Fortran 答案是:use your editor/IDE's block comment tool to do this .

在 Fortran 中,这样的流量控制可以是

if (i_dont_want_to_skip) then
  ! Lots of printing
end if

或(不是 Fortran 90)

printing_block: block
  if (i_do_want_to_skip) exit printing_block
  ! Lots of printing
end block printing_block
<小时/>

但这并不是说应该避免所有 goto,即使可以避免很多/全部。

关于fortran - 我们真的可以在所有情况下都避免 goto 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25553892/

相关文章:

fortran - 根据输入 i,j 从 3x3 中提取次矩阵

fortran - 对 FORTRAN 中的种类感到困惑

fortran - Fortran 数组边界检查的运行时检查未触发

Fortran:管道到程序

c++ - 为什么我的功能在使用 goto 时给我一个 "expected primary-expression before ' }' token"?

java - java中的标签是意大利面条代码吗?

python - 似乎无法让 fortran 可执行文件通过 python 正确运行

python - 读取用 Python 编写的 Fortran 二进制文件

parsing - 将关键字后面的数字从文本文件读取到 Fortran 90 中的数组中

matlab - 在 MATLAB 中转到?