如何将一个具有多个参数的函数传递给一个只有一个参数的子程序?

编程入门 行业动态 更新时间:2024-10-07 16:23:24
本文介绍了如何将一个具有多个参数的函数传递给一个只有一个参数的子程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个子程序(最简单的例子) $ b $ pre $ $ $ c $子程序处理函数$ f $输入$输出$外部, real :: f real,intent(in):: input real,intent(out):: output output = f(input)+ f(1.0)!即f只有一个参数结束子程序

和一个带两个参数的函数

实函数fun(x,a)实数,意图(in):: x,a

现在对于运行时固定的 a ,我想通过 fun 至处理函数。所以理想情况下,我想调用类似于

调用处理函数(fun(:,a = a0),input = myinput,输出= myoutput)

Fortran2003特性 gfortran-5 支持?

当然,我可以在处理函数中插入一个可选的伪参数 a )并调用 f a)取决于子程序正文中的 present(a)。但是改变子程序并不优雅。

解决方案

在Fortran 2008中,您可以将内部函数作为参数传递并且gfortran支持它。顺便说一句,我会远离外部它是邪恶的,使用接口块。

I have a subroutine (minimal example)

subroutine treatfunction(f,input,output) external, real::f real, intent(in):: input real, intent(out):: output output = f(input) + f(1.0) ! i.e. f has only one argument end subroutine

and a function with two arguments

real function fun(x,a) real,intent(in)::x,a

Now for a given a fixed at runtime, I want to pass fun to treatfunction. So ideally, I would want to call something like

call treatfunction(fun(:,a=a0), input=myinput, output=myoutput)

What is the most elegant way of doing this with the Fortran2003 features gfortran-5 supports?

Of course, I could insert an optional dummy argument a in treatfunction and call f either with f(x) or f(x,a) depending on present(a) in the subroutine's body. But changing the subroutine is not elegant.

解决方案

In Fortran 2008 you can pass internal functions as arguments and gfortran supports it.

subroutine calling() a0 = ... call treatfunction(wrapper, input=myinput, output=myoutput) contains real function wrapper(x) real, intent(in) :: x wrapper = fun(x,a0) end function end subroutine

BTW, I would stay away from external it is evil, use interface blocks.

更多推荐

如何将一个具有多个参数的函数传递给一个只有一个参数的子程序?

本文发布于:2023-11-26 23:07:03,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   子程序   多个   只有一个   如何将

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!