我正在研究一个项目(明天到期:/),当我尝试在我自己编写的函数上使用单纯形算法时遇到问题。它没有用,经过5个小时的搜索和实验,我发现了以下内容:
当我将函数传递给子例程时,此函数不能包含任何数组参数。这是真的?因为在我应该使用它的代码中,显然应该工作。
我正在使用ifort编译器。请参阅下面的最小示例,我基本上从http://malayamaarutham.blogspot.de/2006/02/passing-function-names-as-arguments-in.html
中获取 ! Author : Kamaraju S Kusumanchi
! Email : kamaraju@gmail.com
! Last edited : Sun Feb 5 2006
!
! Sample program demonstrating the use of external attribute. This program
! shows how to pass function names as arguments in Fortran 90 programs.
!
! Compilation and execution steps
! $gfortran passing_functions.f90 -o passing_functions
! $./passing_functions
! beta = 5.500000
! beta = 1.500000
!
! I would appreciate any comments, feedback, criticism, mistakes, errors etc.,
! (however minor they are)
!
module dummy
implicit none
contains
!------------------------------------------------------------------------------
function func1(a)
implicit none
real :: a
real :: func1
func1 = a+5
end function func1
!------------------------------------------------------------------------------
function func2(b)
implicit none
real :: b(:)
real :: func2
func2 = b(1)
end function func2
!------------------------------------------------------------------------------
function func3(dyn_func, c)
implicit none
real :: c
real, external :: dyn_func
real :: func3
func3 = dyn_func(c)
end function func3
!------------------------------------------------------------------------------
function func4(dyn_func, c)
implicit none
real :: c(*)
real, external :: dyn_func
real :: func4
func4 = dyn_func(c)
end function func4
end module dummy
!------------------------------------------------------------------------------
program passing_functions
use dummy
implicit none
real :: alpha=0.5, beta
real :: gamma(2) = (/10,20/)
beta = func3(func1, alpha)
write(*,*) 'beta = ', beta
beta = func4(func2, gamma)
write(*,*) 'beta = ', beta
end program passing_functions
这是输出:
zeus$ passing.out
beta = 5.500000
forrtl: severe (174): SIGSEGV, segmentation fault occurred
Image PC Routine Line Source
passing.out 0000000000402D44 Unknown Unknown Unknown
passing.out 0000000000402C7C Unknown Unknown Unknown
libc.so.6 00002AFF7915D23D Unknown Unknown Unknown
passing.out 0000000000402B79 Unknown Unknown Unknown
zeus$
答案 0 :(得分:5)
另一个答案可以用来解决你的问题,但是没有使用指针就有更简单的方法。
在现代Fortran中几乎没有理由使用external
。在我在Stackoverflow上看到的Fortran问题中,它几乎总是导致人们采用错误的方法。除非您确定,否则请勿使用external
。
您要做的是使用func3
块声明(即描述)函数func4
和interface
中的函数参数。以下是func4
的操作方法......您应该能够找出func3
:
function func4(dyn_func, c)
implicit none
real, dimension (:) :: c
interface
function dyn_func (x)
real :: dyn_func
real, dimension (:) :: x
end function dyn_func
end interface
real :: func4
func4 = dyn_func(c)
end function func4