2013-05-12 23 views
0

我正在嘗試適當地構建Fortran程序。我有一個生成我的網格網格的程序GridGeneration.f90。我想在我的主程序中控制網格的大小,即網格大小參數N_x和N_y。這個例子會起作用嗎?Fortran中不同程序中變量之間的鏈接(f90)

module MySubsAndParameters 

implicit none 
integer :: N_x, N_y 

include 'GridGeneration.f90' 

code 

end module MySubsAndParameters 
program main 

use MySubsAndParameters 

N_x = 100 
N_y = 50 

code 

end program main 

如何在GridGeneration.f90中定義N_x和N_y以使其成爲可能?

另外,GridGeneration.f90中定義的變量現在還定義並分配在我的模塊和主程序中?例如,如果在GridGeneration.f90中定義了一個真正的x,我可以在我的主程序中使用它嗎?

回答

1

您的問題是有些不清楚,但可能是以下幫助:

至於模塊變量:每個模塊變量可以通過該模塊中的所有子程序進行訪問,如果它沒有明確地定義private也可以訪問來自主程序。因此,如果您在主程序中給他們一些價值,模塊中的子例程將會意識到這一點。反之亦然,如果您在某些模塊過程中分配它們,主程序將能夠使用它們。

但是,如果你交換nr,這是可能的(並在我的看法更清楚)。通過子程序參數(而不是模塊變量)在主程序和子程序之間的網格點和網格。考慮下面的(我假設你的網格座標爲整數):

module grid 
    implicit none 

contains 

    subroutine gengrid(nx, ny, grid) 
    integer, intent(in) :: nx, ny 
    integer, intent(out) :: grid(:,:) 

    ! create grid based on nx and ny 

    end subroutine gengrid 

end module grid 


program test 
    use grid 
    implicit none 

    integer, allocatable :: mygrid(:,:) 
    integer :: nx, ny 

    nx = 100 
    ny = 50 
    allocate(mygrid(nx, ny)) 
    call gengrid(nx, ny, mygrid) 
    : 

end program test 
  • 通過傳遞網格尺寸明確的套路,它不能發生在你身上,你忘了初始化一些模塊變量從調用例程之前從外部。此外,它立即清楚,例程需要創建網格的變量。

  • 其實你甚至可以騰出的網格大小傳遞給子程序,因爲它可以從分配的數組的大小,猜:

    subroutine gengrid(grid) 
        integer, intent(out) :: grid(:,:) 
    
        integer :: nx, ny 
    
        nx = size(grid, dim=1) 
        ny = size(grid, dim=2) 
        ! create grid based on nx and ny 
    
    end subroutine gengrid 
    
  • 在另一方面,如果你有一個Fortran 2003知道編譯器,您可以將grid作爲allocatable數組傳遞給gengrid例程並在例程內分配它。儘管在Fortran 90中這是不可能的,但我所知道的所有Fortran編譯器都將可分配數組實現爲子例程參數。