具有假定形状虚拟参数的过程必须具有显式接口

val*_*rio 3 fortran function fortran90

我对Fortran 90完全陌生,并且试图了解如何将数组传递给函数。我在网上浏览时,找不到足够清晰和简单的示例,因此决定在此处发布。

我希望函数能够在任何长度的数组上工作(数组的长度不应是函数的参数之一)。

我试图写一个简单的函数示例,该函数返回数组元素的总和:

function mysum(arr)
    implicit none
    real, dimension(:), intent(in) :: arr
    real :: mysum
    integer :: i,arrsize
    arrsize = size(arr)
    mysum=0.0
    do i=1,arrsize
        mysum=mysum+arr(i)
    enddo
end function mysum

program test
    implicit none
    real, dimension(4) :: a
    real :: mysum,a_sum
    call random_number(a)
    print *,a
    a_sum=mysum(a)
    print *,a_sum
end program
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,出现以下错误:

array_test.f90:17.14:

 real mysum,a_sum
           1
Error: Procedure 'mysum' at (1) with assumed-shape dummy argument 'arr' must have an explicit interface
Run Code Online (Sandbox Code Playgroud)

我的程序有什么问题?

Vla*_*r F 5

假设shape虚拟参数(带有的参数(:))需要显式的过程接口,以便在调用站点上可用。这意味着调用代码必须知道子例程头的外观如何。另请参见使用隐式接口调用外部过程的模块

该显式接口可以通过几种方式提供

1. 首选 -模块程序

module procedures
  implicit none

contains

  function mysum(arr)

    real, dimension(:), intent(in) :: arr
    real :: mysum
    integer :: i,arrsize
    arrsize = size(arr)
    mysum=0.0
    do i=1,arrsize
        mysum=mysum+arr(i)
    enddo
  end function mysum
end module

program test
    use procedures

    implicit none
    !no mysum declared here, it comes from the module
    ...
end program
Run Code Online (Sandbox Code Playgroud)

2.内部过程-仅适用于简短的简单过程,或需要访问主机变量的过程。由于可以访问主机变量,因此容易出错。

program test
    implicit none
    !no a_sum declared here, it is visible below contains
    ...    
contains

  function mysum(arr)

    !implicit none inherited from the program

    real, dimension(:), intent(in) :: arr
    real :: mysum
    integer :: i,arrsize
    arrsize = size(arr)
    mysum=0.0
    do i=1,arrsize
        mysum=mysum+arr(i)
    enddo
  end function mysum
end program
Run Code Online (Sandbox Code Playgroud)

3.接口模块- 完全不建议使用,您应该有一些使用它的特殊原因

function mysum(arr)
  ! removed to save space
end function mysum

program test
    implicit none

     interface
       function mysum(arr)
         real, dimension(:), intent(in) :: arr
         real :: mysum
       end function
     end interface

     !no mysum declared there
     !it is declared in the interface block
     ...
end program
Run Code Online (Sandbox Code Playgroud)