2015-07-10 24 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仔細閱讀,它並不簡短,但非常重要。 –

相關問題