我对 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/