2017-02-27 33 views
0

如何避免重複聲明子程序中具有常量值的變量?如何避免在每個子例程中聲明和設置變量的值?

例如:

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 

有時候也有很多是由用戶定義的,我會賺很多使用這些常量子程序的常數,所以我想炒股他們,並利用它們而不是一次又一次地重新定義它們。

+2

你必須使用模塊。另外,不要將'n'稱爲常量。這是一個變量。你正在'read'語句中改變它。 –

+0

請參閱http://stackoverflow.com/questions/42024559/using-global-variables-in-fortran和http://stackoverflow.com/questions/19040118/how-to-avoid-global-variables-in-fortran- 90或更高http://stackoverflow.com/questions/1240510/how-do-you-use-fortran-90-module-data和其他人(可能重複。 –

回答

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模塊。

+0

謝謝,很好,很容易,有沒有另一種如果沒有使用模塊? –

+0

是的,使用通用模塊,我不推薦使用它們現代Fortran是模塊,所以您應該學會盡可能多地使用它們 –

+0

在簡單情況下,您還可以使子例程在程序內部(放在'contains'和'end program'之間) –

相關問題