Fortran使用隐形DO循环和reshape给一维和多维数组赋初值

时间:2022-10-03 16:41:02

Fortran可以使用隐形DO循环和reshape给一维和多维数组赋初值.

下面以一维数组和二维数组为例,并给出程序结果:

program main
implicit none
integer::i,j
integer::a(3)=(/(3*j,j=1,3,1)/)
integer::b(6)=(/((i,i=1,2),4*j,j=1,2,1)/)
real::c(2,4)=reshape((/1,(i,i=3,8),10/),(/2,4/)) write(*,*) 'a(3):',a
write(*,*) 'b(6):',b write(*,*) '!---------------------------------------'
write(*,*) 'c(1,:)',c(1,:)
write(*,*) 'c(2,:)',c(2,:)
write(*,*) '!-----------------------------------------' end program main

输出结果如下:

Fortran使用隐形DO循环和reshape给一维和多维数组赋初值

赋初值时可能符号(/,...,/)看着不太舒服,gfortran容许使用'['和']'来代替:

program main
implicit none
integer::i,j
integer::a(3)=[(3*j,j=1,3,1)]
integer::b(6)=[((i,i=1,2),4*j,j=1,2,1)]
real::c(2,4)=reshape([1,(i,i=3,8),10],(/2,4/)) write(*,*) 'a(3):',a
write(*,*) 'b(6):',b write(*,*) '!---------------------------------------'
write(*,*) 'c(1,:)',c(1,:)
write(*,*) 'c(2,:)',c(2,:)
write(*,*) '!-----------------------------------------' end program main