2015-07-10 22 views
0

我是fortran的新手,想知道是否可以用动态输入编写函数或子程序?例如,如果我想要一个函数/子程序:是否可以在Fortran中使用动态输入编写函数?

function/subroutine a (inputs) 

    integer, dimension(:), allocatable :: b 
    integer :: i,j 

    i = number of inputs 
    allocate(b(i)) 

    do j=1,i 
    b(i)=input(i) 
    end do 

end function a 

所以输入数量可我每次调用该函数/子程序的时间是不同的。可能吗?

+1

Fortran使用可选参数,并且您可以检查此类参数是否存在或不存在。但据我所知,你不能只查询参数的数量,你必须单独检查每个参数。并且都必须在函数的签名中声明。 – innoSPG

+0

如果您在函数中分配并且未返回分配的数组,请记住在退出之前解除分配,否则最终会导致大量内存泄漏。 – cup

+2

@cup自从Fortran 95可分配数组自动释放。我永远不会释放它们。至于Fortran 2003,也适用于所有可分配的实体。 –

回答

3

当所有参数都是同一类型的,你可以把它们放入数组:

subroutine a(inputs) 
    integer :: inputs(:) 
    integer, allocatable :: b(:) 
    integer :: i,j 

    i = size(inputs) 
    allocate(b(i)) 

    do j=1,i 
     b(i)=input(i) 
    end do 

如果他们是不同类型的,你可以使用可选的伪参数。您在访问它之前检查每个参数是否存在必须

subroutine a(in1, in2, in3) 
    integer :: in1 
    real :: in2 
    character :: in3 

    if (present(in1)) process in1 
    if (present(in2)) process in2 
    if (present(in3)) process in3 

您也可以使用泛型,您可以在其中手动指定所有可能的组合,然后编译器然后选择正确的特定过程进行调用。查看您最喜爱的教科书或教程以了解更多内容

module m 

    interface a 
    module procedure a1 
    module procedure a1 
    module procedure a1 
    end interface 

contains 

    subroutine a1(in1) 
    do something with in1 
    end subroutine 

    subroutine a2(in1, in2) 
    do something with in1 and in2 
    end subroutine 

    subroutine a2(in1, in2, in3) 
    do something with in1, in2 and i3 
    end subroutine 

end module 

... 
use m 
call a(x, y) 
+0

当我使用第一个子例程时,它说需要明确的接口。如果我在主程序中包含子程序,它就可以工作。为什么会发生? – user3716774

+0

使用模块http://stackoverflow.com/questions/16486822/fortran-explicit-interface http://stackoverflow.com/questions/11953087/proper-use-of-modules-in-fortran http://stackoverflow.com/questions/8412834 /正确使用模块子程序和fortran-in-fortran仔细阅读,它并不简短,但非常重要。 –

相关问题