在Fortran中创建任意数量的嵌套循环的方法是什么?

时间:2016-03-31 01:15:17

标签: loops recursion nested fortran fortran90

在Fortran中创建任意数量的嵌套循环的方法是什么?例如,以这种方式可以在运行时确定嵌套循环的数量:

do i1 = 1,n1
do i2 = 1,n2
do i3 = 1,n3
do i4 = 1,n4
...
! use i1,i2,i3,i4,....,ik for something
...
enddo
enddo
enddo
enddo

1 个答案:

答案 0 :(得分:0)

因此,如果我理解正确,您需要创建嵌套循环(通常需要将嵌套循环保持在最低限度)。

但是在编译时,你甚至不知道你需要做多少巢。

如果我有这个问题,我可能会将巢打开到一个循环中,并从头开始计算各种指数。这是我刚试过的一个例子:

program nested
    implicit none
    integer :: num_nests, i
    integer, dimension(:), allocatable :: nest_limits
    integer, dimension(:), allocatable :: nests

    print *, "Please enter number of nests:"
    read(*, *) num_nests
    allocate(nest_limits(num_nests))
    allocate(nests(num_nests))

    print *, "Please enter nest limits:"
    read(*, *) nest_limits

    nests(:) = 1
    outer_loop : do
        print *, nests(:)
        i = 1
        ! Calculate the next indices:
        inner_loop : do  
            nests(i) = nests(i) + 1 

            ! If this is still a valid index, exit the inner 
            ! loop and go for the next iteration
            if (nests(i) <= nest_limits(i)) exit inner_loop

            ! The index has overflown, so reset it to 1 and
            ! move to next index.
            nests(i) = 1
            i = i + 1

            ! If the next index would be outside of num_nests, 
            ! the whole loop is finished.
            if (i > num_nests) exit outer_loop

        end do inner_loop
    end do outer_loop
end program nested