将 Fortran 二维数组打印为矩阵 [英] Print a Fortran 2D array as a matrix
问题描述
我有一个当前为 3x3 的数组.当我打印出字符时,我会以环绕线样式打印结果.我希望打印一个更具可读性的方阵而不是 XXXXXXXXXXXXX 在一行上.是否可以使用 do 循环?
I have an array that is currently a 3x3. When I print out the characters, I get the results printed in a wrap-around-line style. I am hoping to print a square matrix that is more readable instead of XXXXXXXXXXXXX on a single line. Is it possible with a do loop?
我有以下几点:
CHARACTER(len=1) :: Grid(2,2)
Grid = "*"
Print *, Grid
推荐答案
根据你想要的输出格式,你不一定需要 do-loop,这里是最简单的:
Depending on the output format you desire, you would not necessarily need a do-loop, here is the simplest:
program simple
implicit none
CHARACTER(len=1) :: Grid(2,2)
Grid = reshape( ["1","2","3","4"] , shape=shape(Grid) )
write( * , "(A)" ) Grid
end program simple
带有 reshape
的行使用 Fortran >2003 数组构造函数语法 []
.因此,请确保您的编译器设置已设置为 Fortran 2008 标准.否则,只需将 []
替换为旧的数组构造函数语法 (//)
.
The line with reshape
, uses the Fortran >2003 array constructor syntax []
. So make sure your compiler settings already is set to Fortran 2008 standard. Otherwise, simply replace []
with the old array constructor syntax (//)
.
如果您希望每一行打印在不同的行上,那么循环将是必要的,至少,一个隐含的do-loop,
If you want each row to be printed on a different line, then looping would be necessary, at least, an implied do-loop,
program simple
implicit none
integer :: i,j
integer, parameter :: n=2
CHARACTER(len=1) :: Grid(n,n)
Grid = reshape( ["1","2","3","4"] , shape=shape(Grid) )
write( * , "(*(g0))" ) ( (Grid(i,j)," ",j=1,n), new_line("A"), i=1,n )
end program simple
我相信,上面的版本避免了编译器创建不必要的临时数组来存储非传染性数组部分Grid(i,:)
,然后再将其打印到输出.g0
编辑描述符是 Fortran 2008 的一个方便的功能.因此请确保您的编译器支持 Fortran 2008 标准.
The above version, I believe, avoids the unnecessary temporary array created by the compiler to store the non-contagious array section Grid(i,:)
, before printing it to the output. The g0
edit descriptor is a handy feature of Fortran 2008. So make sure you compiler supports Fortran 2008 standard.
这篇关于将 Fortran 二维数组打印为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!