用变量值初始化常量

the*_*ux4 4 fortran

program main
   real, parameter :: a = 1 
   !real :: a
   !a=1

   res = func(a)
   write(*,*) res

end program main

function func(a)
   real, parameter :: b=a+1  !(*)
   func = b
   return
end function func
Run Code Online (Sandbox Code Playgroud)

我的编译器在标记为(*)的行处抱怨.有没有办法用一个超出该函数的值来设置常量的值?

M. *_* B. 17

您不能将"b"声明为参数,因为它的值在编译时不是常量,因为它取决于函数参数.

使用"隐式无"是个好主意,因此您一定要声明所有变量.还要将您的过程放入模块并"使用"该模块,以便调用者知道该接口.如:

module my_funcs
implicit none
contains

function func(a)
   real :: func
   real, intent (in) :: a
   real :: b
   b = a + 1
   func = b
   return
end function func

end module my_funcs

program main
   use my_funcs
   implicit none
   real, parameter :: a = 1
   real :: res

   res = func(a)
   write(*,*) res

end program main
Run Code Online (Sandbox Code Playgroud)


dep*_*ted 8

@ MSB的答案很好,如果您可以接受运行时初始化.如果你确实想要一个parameter在编译时设置的Fortran ,那么你可以这样做:

program main
  implicit none
  real, parameter :: a = 1.0
  real :: res

  res = func()
  write(*,*) res

contains
  function func()
    real, parameter :: b = a + 1.0
    real :: func
    func = b
  end function func
end program main
Run Code Online (Sandbox Code Playgroud)

我怀疑部分混乱是由于语言的差异.通常,"参数"用于表示函数的参数,但在Fortran中,它从未以这种方式使用.相反,它意味着与constC/C++ 类似的东西.所以,从你的问题我不清楚你是否真的想要Fortran parameter.

在我上面的例子中,参数a在内部func通过主机关联知道,它是嵌套范围的Fortran术语.您也可以使用模块,通过使用关联来完成它,但它有点冗长:

module mypars
  implicit none
  real, parameter :: a = 1.0
end module mypars

module myfuncs
  implicit none
contains
  function func()
    use mypars, only: a
    real, parameter :: b = a + 1.0
    real :: func
    func = b
  end function func
end module myfuncs

program main
  use myfuncs, only: func
  implicit none
  real :: res
  res = func()
  print *, res
end program main
Run Code Online (Sandbox Code Playgroud)