用变量值初始化常量

问题描述 投票:4回答:2
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

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

fortran
2个回答
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

8
投票

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

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

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

在我上面的例子中,参数afunc中通过主机关联已知,它是嵌套范围的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
© www.soinside.com 2019 - 2024. All rights reserved.