arrays - Fortran 将数组传递给函数

标签 arrays function fortran

我正在尝试将未知长度的数组传递给函数。我也希望 a 的索引与 b 相同。这可能吗?

程序编译但确实运行了函数。

如有任何帮助,我们将不胜感激。

 function RealCumSum(i) result(j)
    real, dimension(1:), intent(in)  :: i ! input
    real, dimension(size(i)) :: j ! output
    integer :: m

    do m = 1,size(i)
        j(m) = sum(i(1:m))
    end do

 end function RealCumSum

 program xfunc
    implicit none
    real, dimension(2) :: a = (/ 3.2 , 2.5 /)
    real, dimension(2) :: b, RealCumSum

    b = RealCumSum(a)

    write(*,*) "cumulative sum of ",a," is ", b
 end program xfunc

最佳答案

假定的形状数组参数 (dimension(:)) 需要一个显式接口(interface)。最好通过将过程放在模块中来完成。其他选项是使过程成为内部过程(使用 contains)或提供 interface block 。

module m
 implicit none
contains
 function RealCumSum(i) result(j)
    real, dimension(1:), intent(in)  :: i ! input
    real, dimension(size(i)) :: j ! output
    integer :: m

    do m = 1,size(i)
        j(m) = sum(i(1:m))
    end do

 end function RealCumSum
end module

 program xfunc
    use m

    implicit none
    real, dimension(2) :: a = (/ 3.2 , 2.5 /)
    real, dimension(2) :: b, RealCumSum

    b = RealCumSum(a)

    write(*,*) "cumulative sum of ",a," is ", b
 end program xfunc

关于arrays - Fortran 将数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26809412/

相关文章:

c - void* 指向二维数组

python - basemap 在经纬度之间画线

c++ - 为什么我必须在 C++ 中的 std::array<SomeStruct, size> 初始化时为每个项目指定类型

python - 根据参数在运行时自定义函数

c - 如何调用以结构体作为参数的函数?

c++ - 在将指针传递给函数后,如何向下转换指针?

fortran - Fortran 中结果变量的用途是什么?

java - 如何打印二维数组的结果

compilation - 链接 lapack 问题

fortran - 如何对文件夹中的所有文件运行 FORTRAN 程序?