问题描述
我有一个如下所示的算法: 10 WRITE(*,*)开始
DO I = 1,10
WRITE(*,*)Step
IF(I .EQ。5)然后
转到10
END IF
END DO
当if语句执行时,我想重新启动循环。但是,我不想用一个去,我试过这个:
10 WRITE(*,*) 开始
DO I = 1,10
WRITE(*,*)Step
IF(I .EQ。5)then
I = 0; CYCLE
END IF
END DO
但是我得到的错误是我无法在循环内重新定义I变量。所以我不知道如何解决这个问题。任何帮助将不胜感激
我可以建议解决此问题的方法:使用while循环或递归函数(高度取决于您的实际算法)。我为这两种情况附上了一个示例代码(请记住,具有save限定符的变量不是最好的想法,通过将变量作为参数传递给函数来实现这一点会更好 - 这里只是为了简单起见) p>
模块函数
隐式无
整数::重新启动,保存= 0
包含
递归子程序restart_loop
integer :: i
do i = 1,10
print *,i
如果(i == 5并且重新启动< 5),则
重新启动=重新启动+ 1
调用restart_loop
出口
结束如果
结束
end子程序restart_loop
子程序while_loop
integer :: i = 1
while(i print *,i
if(i == 5。并且重新启动< 5)然后
i = 1
重新启动=重新启动+ 1
结束如果
i = i + 1
结束do
结束子程序while_loop
结束模块功能
program test_prog
使用函数
隐式无
调用while_loop
结束程序test_prog
I have an algorithm that looks like this:
10 WRITE (*,*) "Start"
DO I = 1, 10
WRITE (*,*) "Step"
IF(I .EQ. 5) then
go to 10
END IF
END DO
I want to restart the loop, when that if statement executes. However, I don't want to have to use a go to, I tried this:
10 WRITE (*,*) "Start"
DO I = 1, 10
WRITE (*,*) "Step"
IF(I .EQ. 5) then
I = 0; CYCLE
END IF
END DO
But then I get the error that I can't redefine the I variable, inside a loop. So I'm not sure how to approach this. Any help would be much appreciated
I can suggest to ways of solving this issue: either use a while loop or a recursive function (highly depends on your actual algorithm). I am attaching a sample code for both cases (keep in mind that having variables with save qualifier is not the best idea, it's much better to do that with by passing variables as arguments to function - here it is used just for simplicity)
module functions
implicit none
integer :: restarted, save = 0
contains
recursive subroutine restart_loop
integer :: i
do i = 1, 10
print*, i
if ( i == 5 .and. restarted < 5 ) then
restarted = restarted + 1
call restart_loop
exit
end if
end do
end subroutine restart_loop
subroutine while_loop
integer :: i = 1
do while (i <= 10)
print*, i
if ( i == 5 .and. restarted < 5 ) then
i = 1
restarted = restarted + 1
end if
i = i + 1
end do
end subroutine while_loop
end module functions
program test_prog
use functions
implicit none
call while_loop
end program test_prog
这篇关于在Fortran中重新启动循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!