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/