问题描述
在下面的子例程中,我想传递一个名为 str
的字符串变量。如果它是'poly'
,'gaus'
,'slat'
,那么它有一个预定义的动作( fval =
参见下面的代码)。我希望让用户指定一个函数来使用并将其作为字符串变量传递。
这就是...
如果 str ='3 * cos(i * t)'
,那么我想要 fval
等于 3 * cos(i * t)
。
子程序f(fval,i, t,str)
隐式无
整数,参数:: ikind = selected_int_kind(8)
整数,参数:: dbl = selected_real_kind(15,307)
整数kind = ikind):: i
real(kind = dbl):: fval,t
character str * 100
if(str .eq。'poly')then
fval = t ** i
elseif(str .eq。'slat')then
fval = exp(-i * t)
elseif(str .eq。'gaus' )然后
fval = exp(-i * t * t)
else
fval = ???
endif
结束子程序
你不能。不容易。但您可以做两件事:
-
首先,您可以使用函数指针。 有一个简单的例子 - 这个想法是,你可以传递在别处定义的函数的名称。这可能足以解决您的问题。
-
您可以调用一个库来解析字符串并评估表达式。我不知道fortran中的任何东西,但是你的Fortran编译器可能支持调用c例程。对于gfortran(也可能是其他人)来说,这看起来好像会起作用 - (例如Fortran代码位于)
In the following subroutine I would like to pass a string variables named str
. If it is 'poly'
, 'gaus'
, 'slat'
, then it has a predefined action (fval =
see code below ). I would like to have the user specify a function to use and pass that as a string variable.
That is ...
If str = '3*cos(i*t)'
, then i would like to have fval
be equal to 3*cos(i*t)
. How can I get Fortran to interpret the string entered as a command to be executed by Fortran?
subroutine f(fval, i, t, str)
implicit none
integer, parameter :: ikind = selected_int_kind(8)
integer, parameter :: dbl = selected_real_kind(15,307)
integer(kind = ikind) :: i
real(kind = dbl) :: fval, t
character str*100
if(str .eq. 'poly') then
fval = t**i
elseif(str .eq. 'slat') then
fval = exp(-i*t)
elseif(str .eq. 'gaus') then
fval = exp(-i*t*t)
else
fval = ???
endif
end subroutine
you can't. not easily. there are two things you can do, though:
first, you can use function pointers. there's a simple example at http://www.macresearch.org/advanced_fortran_90_callbacks_with_the_transfer_function - the idea is that you can pass the name of a function defined elsewhere. that may be enough to solve your problem.
you can call a library that parses the string and evaluates the expression. i don't know of anything in fortran, but your fortran compiler may support calling c routines. for gfortran (and maybe others), this looks like it would work - http://www.gnu.org/s/libmatheval/ (example fortran code at http://www.gnu.org/s/libmatheval/manual/libmatheval.html#Fortran-sample-program)
这篇关于传递字符串以在Fortran子例程中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!