Declaring variables in function (Fortran)

独自空忆成欢 提交于 2020-01-24 20:08:06

问题


I am trying to write a very simple function in Fortran (first-time user):

program Main 
  implicit none 
  integer function k(n) 
    integer, intent(in) :: n 
    k=n 
   end function k 
 end program Main

I get a bunch of errors:

integer function k(n)
                  1
Error: Syntax error in data declaration at (1)

   integer, intent(in) :: n
                          1
Error: Unexpected data declaration statement at (1)

   end function k
     1
Error: Expecting END PROGRAM statement at (1)

   k=n
   1
Error: Symbol ‘k’ at (1) has no IMPLICIT type

   k=n
     1
Error: Symbol ‘n’ at (1) has no IMPLICIT type

What am I doing wrong? I'm using the last version of gfortran.


回答1:


Any declared functions and subroutines local to the program block should be put after a contains statement, for example

program Main 
  implicit none 
 contains
  integer function k(n) 
    integer, intent(in) :: n 
    k=n 
   end function k 
end program Main

To give an example of a program using this you could have

program Main 
  implicit none 
  integer :: myLocalN
  myLocalN = 2
  print*, "My local N is ", myLocalN
  print*, "The value of this squared is", sq(myLocalN)
 contains
  integer function sq(n) 
    integer, intent(in) :: n 
    sq=n*n 
   end function sq
end program Main


来源:https://stackoverflow.com/questions/37676874/declaring-variables-in-function-fortran

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!