2012-01-15 147 views
4
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 

我的编译器在标有(*)的行上抱怨。有没有一种方法可以设置一个常量的值,该值的值超出该函数的范围?用变量的值初始化常量

回答

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

在我的例子上文中,参数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