我是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
我的程序有什么问题?
假定的形状虚拟参数(具有(:)
)需要显式接口 可以在呼叫网站上可用。这意味着通话代码必须知道子例程标头的样子。另请参阅模块调用带有隐式接口的外部过程
可以通过多种方式提供显式接口
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。接口块 - 根本不建议使用,您应该有一些特殊的理由
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