fortran定义数组

在 Fortran 中,声明一个数组可以通过 dimension 属性来定义数组的维度。根据数组的使用场景,可以使用静态数组动态数组

1. 静态数组声明

静态数组是在声明时直接定义好数组的大小,数组的大小在编译时确定。

示例 1:一维静态数组
program static_array_example
  implicit none
  real :: array1(5)  ! 声明一个长度为5的实数数组

  ! 给数组赋值
  array1 = (/ 1.0, 2.0, 3.0, 4.0, 5.0 /)

  ! 打印数组元素
  print *, "Array elements:", array1
end program static_array_example
示例 2:二维静态数组
program static_2d_array_example
  implicit none
  real :: matrix(3, 3)  ! 声明一个3x3的二维实数数组

  ! 给矩阵赋值
  matrix = reshape([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], shape(matrix))

  ! 打印矩阵
  print *, "Matrix:"
  print *, matrix
end program static_2d_array_example

2. 动态数组声明

动态数组的大小在程序运行时确定,通常用于处理不确定大小的数据。可以使用 allocatable 来声明动态数组,并使用 allocate 在运行时为数组分配内存。

示例 1:一维动态数组
program dynamic_array_example
  implicit none
  integer :: n
  real, dimension(:), allocatable :: array1

  ! 获取数组大小
  print *, "Enter the size of the array:"
  read *, n

  ! 分配内存
  allocate(array1(n))

  ! 给数组赋值
  array1 = 1.0  ! 将所有元素设置为 1.0

  ! 打印数组
  print *, "Array elements:", array1

  ! 释放数组
  deallocate(array1)
end program dynamic_array_example
示例 2:二维动态数组
program dynamic_2d_array_example
  implicit none
  integer :: rows, cols
  real, dimension(:,:), allocatable :: matrix

  ! 获取行数和列数
  print *, "Enter the number of rows and columns:"
  read *, rows, cols

  ! 分配内存
  allocate(matrix(rows, cols))

  ! 给矩阵赋值
  matrix = 0.0  ! 初始化所有元素为 0.0

  ! 打印矩阵
  print *, "Matrix:"
  print *, matrix

  ! 释放内存
  deallocate(matrix)
end program dynamic_2d_array_example

3. 数组的多种声明方式

一维数组(长度为5)
real :: array1(5)  ! 实数数组,大小为5
integer :: array2(5)  ! 整数数组,大小为5
多维数组(3x4)
real :: matrix(3, 4)  ! 实数二维数组,大小为3行4列
integer :: tensor(2, 3, 4)  ! 整数三维数组
动态数组
real, dimension(:), allocatable :: dynamic_array1  ! 动态分配一维数组
real, dimension(:,:), allocatable :: dynamic_matrix  ! 动态分配二维数组

总结

  • 静态数组:在编译时定义大小,适用于已知大小的数据。
  • 动态数组:在运行时分配内存,适用于大小不确定的数据。
  • Fortran 数组支持多维声明,维度可以根据程序的需要进行扩展
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值