如何传递返回数组作为FORTRAN中的参数的函数 [英] How to pass a function returning an array as an argument in FORTRAN

查看:290
本文介绍了如何传递返回数组作为FORTRAN中的参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this function f, that returns an array, and this function f is given as an argument to a function g, example:

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数组索引|
您能帮我吗?

But at the line g=f(1.1) it goes wrong, fortran thinks 1.1 is the index of the array f instead of the value which f has to evaluate. The literal error is: ||Error: Legacy Extension: REAL array index | Can you help me?

推荐答案

您可以执行此操作,但必须明确定义 g 函数中的> f 是返回两个实数的函数,而不是返回两个实数的数组的函数。诚然,fortran中用于描述函数的返回类型的约定使这种区分不如应有的明显。

You can do this, but you have to explicitly define f in the g function as being a function which returns two reals, rather than an array 2 two reals. Admittedly, the convention that's used in fortran for describing the return type of a function makes that distinction less obvious than it should be.

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

The way you define something to be of type function is with an interface block; that interface block describes both the function's return type and its argument list. It basically just looks like the first few lines of the declaration of the function, with the body of the function deleted. (I'm saying "function" here, but really should be saying "subprograms"; it works the same way with subroutines). Then the compiler knows both what the return value of the function is, but also the argument list. An interface block is something like a function prototype in C-based languages.

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

Using an interface block for your argument looks like this:

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

这篇关于如何传递返回数组作为FORTRAN中的参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆