如何避免在子程序中重复声明具有常量值的变量?
例如:
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
Run Code Online (Sandbox Code Playgroud)
有时,有很多由用户定义的常量,我会制作很多使用这些常量的子例程,所以我想存储它们并使用它们,而不是一次又一次地重新定义它们。
对于全局变量,使用模块(旧的 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
Run Code Online (Sandbox Code Playgroud)
Stack Overflow 上有很多问题和答案解释如何正确使用 Fortran 模块。