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

时间:2017-02-27 10:45:18

标签: fortran fortran90

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

例如:

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

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

1 个答案:

答案 0 :(得分:2)

对于全局变量使用模块(旧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模块。