【问题标题】:How to pass a function returning an array as an argument in FORTRAN如何在 FORTRAN 中传递返回数组作为参数的函数
【发布时间】:2014-04-07 21:49:30
【问题描述】:

我有这个函数 f,它返回一个数组,这个函数 f 作为函数 g 的参数给出,例如:

function f(a)
 real, dimension(2)::f
 real a
 f(1)=a
 f(2)=a+1
end function

function g(f)
 real, dimension(2)::f,g
 g=f(1.1)
end function

但是在 g=f(1.1) 行出错了,fortran 认为 1.1 是数组 f 的索引,而不是 f 必须评估的值。 字面错误是: ||错误:传统扩展:REAL 数组索引 | 你能帮帮我吗?

【问题讨论】:

标签: arrays function fortran


【解决方案1】:

您可以这样做,但您必须在 g 函数中明确定义 f 作为返回两个实数的函数,而不是返回两个实数的数组 2。诚然,fortran 中用于描述函数返回类型的约定使得这种区别不像应有的那么明显。

定义函数类型的方式是使用interface block;该接口块描述了函数的返回类型及其参数列表。它基本上看起来就像函数声明的前几行,删除了函数体。 (我在这里说的是“函数”,但实际上应该说的是“子程序”;它与子例程的工作方式相同)。然后编译器既知道函数的返回值是什么,也知道参数列表。接口块类似于基于 C 语言的函数原型。

为参数使用接口块如下所示:

module functions
implicit none

contains

    function f(a)
     real, dimension(2)::f
     real, intent(in) :: a
     f(1)=a
     f(2)=a+1
    end function

    function g(f)
     real, dimension(2)::g
     interface
        function f(x)
            real, dimension(2) :: f
            real, intent(in) :: x
        end function f
     end interface

     g=f(1.1)

    end function

end module functions

program test
    use functions
    implicit none

    real, dimension(2) :: result

    result = g(f)
    print *, 'result = ', result
end program test

结果如你所愿:

$ gfortran -o interface_ex interface_ex.f90
$ ./interface_ex
 result =    1.1000000       2.0999999

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-06
    • 2015-10-23
    • 2018-04-09
    • 2015-12-09
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多