function - 具有假定形状虚拟参数的过程必须具有显式接口(interface)

标签 function fortran 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

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

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

我的程序有什么问题?

最佳答案

假定的形状虚拟参数(带有 (:) 的参数)需要调用站点上可用的过程的显式接口(interface)。这意味着调用代码必须知道子例程 header 到底是什么样子。另请参阅Module calling an external procedure with implicit interface

可以通过多种方式提供显式接口(interface)

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

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

3. 界面 block - 完全不推荐,您应该有一些特殊的理由来使用它

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

关于function - 具有假定形状虚拟参数的过程必须具有显式接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42766530/

相关文章:

c# - 如何创建一个获取未知数量值的方法?

dependencies - 用于自动依赖项生成的英特尔 Fortran 编译器选项

fortran - Fortran 输出时给字符串添加空格

compilation - 此 FORTRAN 代码不应编译。这是有原因的吗?

fortran - Fortran 90 中的优化例程

Javascript if 变量等于变量启用函数

javascript - 从 angularjs 中的嵌套成功函数返回一个值

javascript - 如何在javascript Filter函数中过滤掉NaN

python - f2py 和 gfortran : undefined reference to `main' 编译错误

fortran - 宽度为零的格式描述符,如 F0.6 或 G0.8