从Fortran函数返回实向量

时间:2019-01-02 17:23:51

标签: fortran gfortran

我刚开始使用Fortran,我想编写一个简单的函数,该函数将三个实数作为参数并返回包含3个实数的向量,但是我在使用Fortran语法时遇到困难:

function foo(x,y,z) result(res)
    real, intent(in) :: x,y,z
    real, intent(out) :: res(3)
    res=[x**x,y**y,z**z]
end function foo

program function_test
    implicit none
    real :: res(3)                      !declare the array res
    real :: foo(3)                      !declare the return type of the function foo
    res=foo(1.0,1.0,1.0)                !call foo and save the resulting vector in res
    print *,"1st component:",res(1)     !Print the first element of the result array
    print *,"2nd component:",res(2)     !Print the second element of the result array
    print *,"3rd component:",res(3)     !Print the third element of the result array
end program function_test

使用gfortran编译以上代码会导致错误消息Error: Rank mismatch in array reference at (1) (3/1)。现在,我了解到语句res=foo(1.0,1.0,1.0)似乎被解释为“采用三维数组foo的元素[1,1,1]”,这当然是不正确的,但是如何调用foo并将结果数组存储在res中?

(据我了解,real :: foo(3)中的行function_test对于定义foo的返回类型是必需的。)

0 个答案:

没有答案