定义返回数组的函数

hba*_*ega 4 arrays fortran function fortran90

我有以下代码:

    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
Run Code Online (Sandbox Code Playgroud)

我想让程序确实用于"作为arrray的功能",即我想替换Subroutine funcby function f和得到相同的结果(在主程序中,我希望保持一个声明y=f(x,N)).我怎样才能做到这一点?

谢谢.

Jon*_*rsi 8

还有有一个函数返回一个数组,如没有问题这个问题,回答:主要的问题是,你需要的功能是一个模块(或contain程序中的ED),这样有一个自动显式接口:(编辑添加:或者像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
Run Code Online (Sandbox Code Playgroud)

但请注意,这种函数 - 对数组中的每个元素应用相同的操作 - 使用Fortran elemental函数更好一些,Fortran 函数被定义为仅在标量上工作,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
Run Code Online (Sandbox Code Playgroud)

关于这一点的好处是它现在可以自动处理标量和任何等级的数组.只要有可能,让编译器为您完成工作是件好事.