Fortran 我们真的能在所有情况下都避免后继吗?
Fortran 90及更高版本强烈建议不要使用Fortran 我们真的能在所有情况下都避免后继吗?,fortran,fortran90,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 p
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
在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
bump
案例2 非Fortran的答案是: 在Fortran中,这样的流控制可以
if (i_dont_want_to_skip) then
! Lots of printing
end if
或者(这不是Fortran 90)
但这并不是说应该避免所有的
goto
s,即使很多/all都可以避免。根据您所说的“程序的连续部分”的含义,情况2可能会跳出某些块结构,例如:
do i = 1,n
...
goto 1
...
enddo
...
1 continue
如果您遇到这种情况,那么要解开代码逻辑并用现代结构化编码取代它可能是一个相当大的挑战。更重要的是,不要用这种方式“注释”..案例2的另一种可能性是使用预处理器指令。事实上,这是一个很好的观点。虽然我把它作为一种非Fortran的方式,但它非常类似于
if
构造。从理论角度回答标题问题:谢谢大家的讨论@PetrH,你能详细解释一下“预处理器指令”是什么意思吗?
printing_block: block
if (i_do_want_to_skip) exit printing_block
! Lots of printing
end block printing_block
do i = 1,n
...
goto 1
...
enddo
...
1 continue