2017-09-01 31 views
1

我正在將一個子例程鏈接到Fortran中的另一個調用程序。我無法訪問調用程序。調用程序根據用戶輸入開關傳遞我的程序單精度數字或雙精度數字。例如,這裏的一些代碼如何在Fortran中檢查REAL是否作爲DOUBLE傳遞?

subroutine myCode(x) 
implicit double precision (a-h,o-z) 
! do something with x 
end subroutine myCode 

同樣,調用程序可通過x作爲單精度數的作爲雙精度數。如果x作爲單精度數字傳遞,我希望我的程序失敗。 「x」的值可以是任何正實數。

有沒有一種方法可以測試x以查看它是單精度數還是雙精度數?

+0

使用功能'那種(X)':如果'種(X) == kind(1.)'那麼它是一個單精度數elseif'kind(x)== kind(1.d)'那麼它是一個雙精度數。 –

+2

沒有Fortran方法:只要將默認實參傳遞給參數,就不會再有Fortran程序。 – francescalus

+1

使用模塊。所有的子程序都應該放在一個模塊中。編譯器可以檢查一切是否正確傳遞。 –

回答

3

我想檢查什麼實際傳遞的唯一方式是重載哪一個被稱爲程序和測試:

module kinds_mod 
    use iso_fortran_env, only: real32, real64 
    implicit none 
    interface my_double 
     module procedure my_double_r32, my_double_r64 
    end interface 

    public :: my_double 
    private :: my_double_r32, my_double_r64 

contains 

    function my_double_r32(val) result(d) 
     real(kind=real32), intent(in) :: val 
     real(kind=real32) :: d 
     d = val * 2.0_real32 
     print*, "called for 32 bit real" 
    end function my_double_r32 

    function my_double_r64(val) result(d) 
     real(kind=real64), intent(in) :: val 
     real(kind=real64) :: d 
     d = val * 2.0_real64 
     print*, "called for 64 bit real" 
    end function my_double_r64 

end module kinds_mod 

program test_kinds 
    use kinds_mod 
    implicit none 
    real :: r, r2 
    double precision :: d, d2 

    r = 2.0 
    d = 4.0_8 

    print*, "calling for single precision" 
    r2 = my_double(r) 
    print *, r, r2, kind(r) 
    print*, "calling for double precision" 
    d2 = my_double(d) 
    print *, d, d2, kind(d) 
end program test_kinds 
相關問題