我有以下模块:
module prestel
implicit none
contains
subroutine gradient(rho,N,gradiant_rho)
implicit none
real(kind=real), allocatable :: rho(:)
real(kind=real),allocatable :: gradiant_rho(:)
integer,intent(in) :: N
integer :: i
do i = 1,N
gradiant_rho(i) = rho(i) - 2
end do
end subroutine gradient
subroutine state_system(density,N,grad_density)
implicit none
real(kind=real), allocatable :: density(:)
real(kind=real), allocatable :: grad_density(:)
integer :: i,j
integer, intent(in) :: N
call gradient(density,velocity,N,grad_density,grad_velocity)
do i=1,N
density (i+1) = density(i) - 2*grad_density(i))
end do
end subroutine state_system
end module prestel
现在子程序"状态系统";使用第一个子程序"gradient"。我们从初始数组密度开始以及"国家体系"子例程对数组中的每个元素执行操作,直到得到修改后的新数组。
现在我的问题是,我需要把它放在一个循环中(比如,do j=1,10)。因此,在这个循环的每次迭代中,子例程(系统状态和梯度)将返回一个修改后的数组,然后我希望我的程序用获得的新数组替换旧数组(这是两个子例程的输入)并再次执行。
我不知道如何在每次迭代时更新子例程中的这两个数组。我试着定义一个新的数组,并把所有的新值,但它没有导致任何地方。
如果我想这样做,我应该把循环时调用子程序在主程序,或子程序内?
你应该把循环放在主程序中,每次你调用state_system
子程序,density
数组得到更新,并再次被馈送到子程序,等等。
module prestel_m
implicit none
private
public state_system
contains
subroutine gradient(density, gradiant_density)
real, intent(in) :: density(:)
real, intent(out) :: gradiant_density(:)
gradiant_density = density - 2
end subroutine gradient
subroutine state_system(density)
real, intent(inout) :: density(:)
real, allocatable :: grad_density(:)
allocate (grad_density(size(density)))
call gradient(density, grad_density)
density = density - 2*grad_density
end subroutine
end module
program test_state_system
use prestel_m
integer, parameter :: n = 5 ! just for this example
real, allocatable :: density(:)
integer :: j
allocate (density(n))
call random_number(density) ! just for this example
do j = 1, 10
! here, you get updated version of 'density' for each iteration
call state_system(density)
end do
end program
我不是100%确定正确理解你的问题,但尽管如此,下面的代码应该沿着你的意图可能是做一些事情。如果我误解了你的问题,请不要犹豫,给我反馈。
module prestel_m
implicit none
private
public state_system
contains
subroutine gradient(density, gradiant_density)
real, intent(in) :: density(:)
real, intent(out) :: gradiant_density(:)
gradiant_density = density - 2
end subroutine gradient
subroutine state_system(density)
real, intent(inout) :: density(:)
integer :: j
real, allocatable :: grad_density(:)
allocate (grad_density(size(density)))
do j = 1, 10
call gradient(density, grad_density)
density = density - 2*grad_density
end do
end subroutine
end module