如何避免在每个子程序中声明和设置变量的值?

How to avoid declaring and setting the value of a variable in each subroutine?

如何避免在子程序中重复声明具有常量值的变量?

例如:

program test
  implicit none

  integer :: n
  integer :: time

  print*, "enter n" ! this will be a constant value for the whole program
  call Calcul(time)
  print*, time  
end program

subroutine Calcul(Time)
  implicit none

  integer :: time 

  ! i don't want to declare the constant n again and again because some times the subroutines have a lot of variables.  
  time = n*2 
end subroutine

有时会有很多用户定义的常量,我会制作很多使用这些常量的子程序,所以我想储存它们并使用它们而不用一次又一次地重新定义它们。

对于全局变量使用模块(旧的 FORTRAN 使用公共块,但它们已过时):

module globals
  implicit none

  integer :: n

contains

  subroutine read_globals()    !you must call this subroutine at program start

    print*, "enter n" ! this will be a constant value for the whole program
    read *, n
  end subroutine
end module

!this subroutine should be better in a module too !!!
subroutine Calcul(Time)
  use globals !n comes from here
  implicit none

  integer :: time 
  time = n*2
end subroutine

program test
  use globals ! n comes from here if needed
  implicit none

  integer :: time

  call read_globals()

  call Calcul(time)

  print*, time
end program

Stack Overflow 上有很多解释如何正确使用 Fortran 模块的问题和答案。