Fortran将数组传递给函数 [英] Fortran pass an array to function

查看:482
本文介绍了Fortran将数组传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to pass an array of unknown length to a function. I would also prefer the indices of a is the same as b. Is this possible?

该程序可以编译,但可以通过该函数运行.

The program compiles but does run through the function.

任何帮助将不胜感激.

 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(:))需要一个显式接口.最好通过将过程放在模块中来完成.其他选项是使过程成为内部过程(使用contains)或提供interface块.

The assumed shape array arguments (dimension(:)) require an explicit interface. It is best done by placing the procedure in a module. The other options are to make the procedure internal (using contains) or to supply an 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

这篇关于Fortran将数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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