Fortran 动态数组

动态数组是一个数组,其大小在编译时未知,但在执行时已知。

动态数组使用属性 allocatable 声明。

例如:

  1. real, dimension (:,:), allocatable :: darray

数组的维度,必须提及,但是,要为这样的数组分配内存,您可以使用 allocate 函数。

  1. allocate ( darray(s1,s2) )

使用数组后,在程序中,应使用解除分配函数释放创建的内存。

  1. deallocate (darray)
实例
  1. program dynamic_array
  2. implicit none
  3. !rank is 2, but size not known
  4. real, dimension (:,:), allocatable :: darray
  5. integer :: s1, s2
  6. integer :: i, j
  7. print*, "Enter the size of the array:"
  8. read*, s1, s2
  9. ! allocate memory
  10. allocate ( darray(s1,s2) )
  11. do i = 1, s1
  12. do j = 1, s2
  13. darray(i,j) = i*j
  14. print*, "darray(",i,",",j,") = ", darray(i,j)
  15. end do
  16. end do
  17. deallocate (darray)
  18. end program dynamic_array

结果如下:

  1. Enter the size of the array: 3,4
  2. darray( 1 , 1 ) = 1.00000000
  3. darray( 1 , 2 ) = 2.00000000
  4. darray( 1 , 3 ) = 3.00000000
  5. darray( 1 , 4 ) = 4.00000000
  6. darray( 2 , 1 ) = 2.00000000
  7. darray( 2 , 2 ) = 4.00000000
  8. darray( 2 , 3 ) = 6.00000000
  9. darray( 2 , 4 ) = 8.00000000
  10. darray( 3 , 1 ) = 3.00000000
  11. darray( 3 , 2 ) = 6.00000000
  12. darray( 3 , 3 ) = 9.00000000
  13. darray( 3 , 4 ) = 12.0000000

数据声明的使用

数据语句可用于初始化多个数组,或用于数组段初始化。

数据语句的语法为:

  1. data variable / list / ...
实例
  1. program dataStatement
  2. implicit none
  3. integer :: a(5), b(3,3), c(10),i, j
  4. data a /7,8,9,10,11/
  5. data b(1,:) /1,1,1/
  6. data b(2,:)/2,2,2/
  7. data b(3,:)/3,3,3/
  8. data (c(i),i = 1,10,2) /4,5,6,7,8/
  9. data (c(i),i = 2,10,2)/5*2/
  10. Print *, 'The A array:'
  11. do j = 1, 5
  12. print*, a(j)
  13. end do
  14. Print *, 'The B array:'
  15. do i = lbound(b,1), ubound(b,1)
  16. write(*,*) (b(i,j), j = lbound(b,2), ubound(b,2))
  17. end do
  18. Print *, 'The C array:'
  19. do j = 1, 10
  20. print*, c(j)
  21. end do
  22. end program dataStatement

结果如下:

  1. The A array:
  2. 7
  3. 8
  4. 9
  5. 10
  6. 11
  7. The B array:
  8. 1 1 1
  9. 2 2 2
  10. 3 3 3
  11. The C array:
  12. 4
  13. 2
  14. 5
  15. 2
  16. 6
  17. 2
  18. 7
  19. 2
  20. 8
  21. 2

Where 语句的使用

where 语句可以让您在表达式中使用数组的某些元素,具体取决于某些逻辑条件的结果。如果给定的条件为 true,它允许在元素上执行表达式。

实例
  1. program whereStatement
  2. implicit none
  3. integer :: a(3,5), i , j
  4. do i = 1,3
  5. do j = 1, 5
  6. a(i,j) = j-i
  7. end do
  8. end do
  9. Print *, 'The A array:'
  10. do i = lbound(a,1), ubound(a,1)
  11. write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))
  12. end do
  13. where( a<0 )
  14. a = 1
  15. elsewhere
  16. a = 5
  17. end where
  18. Print *, 'The A array:'
  19. do i = lbound(a,1), ubound(a,1)
  20. write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))
  21. end do
  22. end program whereStatement

结果如下:

  1. The A array:
  2. 0 1 2 3 4
  3. -1 0 1 2 3
  4. -2 -1 0 1 2
  5. The A array:
  6. 5 5 5 5 5
  7. 1 5 5 5 5
  8. 1 1 5 5 5

分类导航