将Fortran 2D阵列打印为矩阵 [英] Print a Fortran 2D array as a matrix

查看:97
本文介绍了将Fortran 2D阵列打印为矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个当前为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循环,这是最简单的:

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 (//).

如果您希望将每一行打印在不同的行上,则至少需要隐式循环

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 2D阵列打印为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆