我有以下代码:
Program function_as_an_array
implicit none
integer:: i
integer, parameter:: N=10
real*8:: x(N),y(N),f(N)
do i=1,N
x(i)=float(i)
end do
call func(f,N,x)
open(unit=20, file='test.dat')
do i=1,N
y(i)=f(i)
write(20,*) x(i),y(i)
end do
close(20)
Stop
End Program function_as_an_array
Subroutine func(f,N,x)
implicit none
integer i,N
real*8:: x(N),f(N)
do i=1,N
f(i)=x(i)**2
end do
end Subroutine func
我想使程序确实适用于“作为错误的功能”,即我想用Subroutine func
替换function f
并得到相同的结果(在主程序中,我希望保留类似y=f(x,N)
的语句)。我该怎么办?
[与this question and answer一样,函数返回数组没有问题:主要问题是您需要将该函数放在模块中(或在程序中包含contain
),以便有一个自动的显式接口: (编辑以添加:或像Alexander Vogt的答案一样明确定义接口)
module functions
contains
function func(N,x)
implicit none
integer, intent(in) :: N
double precision, intent(in) :: x(N)
double precision, dimension(N) :: func
integer :: i
do i=1,N
func(i)=x(i)**2
end do
end function func
end module functions
Program function_as_an_array
use functions
implicit none
integer:: i
integer, parameter:: N=10
double precision:: x(N),y(N)
do i=1,N
x(i)=float(i)
end do
y = func(N,x)
open(unit=20, file='test.dat')
do i=1,N
write(20,*) x(i),y(i)
end do
close(20)
Stop
End Program function_as_an_array
但是请注意,这种函数-对数组中的每个元素应用相同的操作-可以通过Fortran elemental
函数(定义为仅在标量上运行)更好地完成,并且Fortran会自动将其映射到适合您的数组:
module functions
contains
elemental double precision function f(x)
implicit none
double precision, intent(in) :: x
f = x**2
end function f
end module functions
Program function_as_an_array
use functions
implicit none
integer:: i
integer, parameter:: N=10
double precision:: x(N),y(N)
do i=1,N
x(i)=float(i)
end do
y = f(x)
open(unit=20, file='test.dat')
do i=1,N
write(20,*) x(i),y(i)
end do
close(20)
Stop
End Program function_as_an_array
有趣的是,它现在可以在标量上自动运行,并且可以自动排列任何等级的数组。尽可能让编译器为您完成工作。
这对我有用:
Program function_as_an_array
implicit none
integer:: i
integer, parameter:: N=10
real*8 :: x(N),y(N),f(N)
interface func
function func(x,N) result(f)
implicit none
integer N
real*8:: x(N),f(N)
end function
end interface
do i=1,N
x(i)=float(i)
end do
f = func(x,N)
open(unit=20, file='test.dat')
do i=1,N
y(i)=f(i)
write(20,*) x(i),y(i)
end do
close(20)
Stop
End Program function_as_an_array
function func(x,N) result(f)
implicit none
integer i, N
real*8:: x(N),f(N)
do i=1,N
f(i)=x(i)**2
end do
end function
您需要:
result
表示数组值的返回变量[edit]或将func指定为real*8:: func(N)
。有关详细信息,请参见注释。 然后,您可以直接将函数的返回值分配给数组。