如何避免在每个子例程中声明和设置变量的值? [英] How to avoid declaring and setting the value of a variable in each subroutine?
本文介绍了如何避免在每个子例程中声明和设置变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何避免在子例程中重复声明一个具有常量值的变量?
例如:pre>
程序测试
隐含无
整数:: n
整数::时间
print *,输入n!这将是一个不变的价值为整个程序
调用Calcul(时间)
print *,时间
结束程序
子程序Calcul(时间)
隐含无
整数::时间
!我不想一次又一次地声明常量n,因为有些时候子例程有很多变量。
时间= n * 2
结束子程序
<有时,有很多常量是由用户定义的,我会做很多使用这些常量的子例程,所以我想将它们存储起来并使用它们,而不必一次又一次地重新定义它们。
解决方案
对于全局变量,使用模块(旧的FORTRAN使用的通用块,但它们已经过时):
模块全局变量
隐式无
整型:: n
包含
子例程read_globals()!你必须在程序开始时调用这个子程序
print *,enter n!这对于整个程序来说是一个常数值
read *,n
结束子程序
结束模块
!这个子程序在模块中应该更好! !
子程序Calcul(Time)
使用全局变量!n来自这里
隐含无
整数::时间$ b $时间= n * 2
结束子程序
程序测试
使用全局变量!如果需要,n来自这里
隐式无
整数::时间
调用read_globals()
调用Calcul(time)
print *,time
end program
有很多问题并解释如何在堆栈溢出中正确使用Fortran模块。
How to avoid repeated declaration of a variable that has a constant value in subroutines?
For example:
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
Sometimes there are a lot of constants that are defined by the user and I will make a lot of subroutines that use those constants, so I want to stock them and and use them without redefining them again and again.
解决方案
For global variables use modules (old FORTRAN used common blocks, but they are obsolete):
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
There are many questions and answers explaining how to use Fortran modules properly on Stack Overflow.
这篇关于如何避免在每个子例程中声明和设置变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文