Fortran级联可选参数

时间:2015-03-30 01:41:43

标签: fortran optional

我在使用可选参数时遇到问题。我有两个例程num_to_strqry,它们采用格式fm作为可选参数。当我打电话给qry ("lc")时,尽管如此 fm不存在,例程num_to_str认为fm存在。

Call qry ("lc")

Subroutine qry (lb, fm)
  Character (Len=*), Intent (In), Optional :: lb, fm
  Real :: n 
  Character (Len=65) :: s 

  n = 90.0
  Call num_to_str (n, s, fm)
End Subroutine

Subroutine num_to_str (nb, s, fm)
  Real, Intent (In) :: nb
  Character (Len=*), Intent (In) :: s
  Character (Len=*), Intent (In), Optional :: fm

  fmt = "*"
  if (Present (fm)) fmt = Trim (fm)
End Subroutine  

1 个答案:

答案 0 :(得分:0)

以下适用于intel fortran和gfortran,

module stuff
  implicit none

contains 

  Subroutine qry (lb, fm)
    Character (Len=*), Intent (In), Optional :: lb, fm
    Real :: n 
    Character (Len=65) :: s

    n = 90.0
    s = "test"
    Call num_to_str (n, s, fm)
  End Subroutine

  Subroutine num_to_str (nb, s, fm)
    Real, Intent (In) :: nb
    Character (Len=*), Intent (In) :: s
    Character (Len=*), Intent (In), Optional :: fm
    Character (Len=65)  :: fmt

    fmt = "*"
    if (Present (fm)) then 
        fmt = Trim (fm)
        print*, nb, s, fm
    else
        print*, nb, s
    endif
  End Subroutine  

end module stuff

program test
  use stuff, only : qry

  Call qry("lc")
  Call qry("lc","f12")

end program test

带输出

 $ ./a.out 
 90.000000     test                                                             
 90.000000     test               f12

使用可选参数时,应始终使用模块(或显式接口)。看看这个answer