在Fortran90格式描述符中使用参数

时间:2015-06-05 09:37:09

标签: format fortran fortran90 gfortran

如何在Fortran90中使用格式描述符中的参数?

我想制作一个矩阵,比如square(n * n),但我想把它变成一般的。所以,我宣布了一个像这样的参数:integer,parameter::n=3(比如n在这里是3)

然后在do / implied do循环中输入矩阵的元素后,我想用格式函数编写它,如下所示:

format(ni5)

但它给出了错误:Unexpected element 'N' in format string 任何解决这个问题的简单方法??

1 个答案:

答案 0 :(得分:0)

Little-known fact: format specifiers can be constructed at runtime as a character string. This means that you can programmatically define the format specifier and pass it to the write statement.

CHARACTER(len=30) fm
INTEGER :: i
i = 3
WRITE(fm,'(a,i1,a)')"(",i,"i5)"

WRITE(*,fm)1,2,3

In the above, we are generating the actual format specifier with the number of integers that you need to print for the given situation (i), then using that string as the format of the second write statement.

I very rarely see people use this trick, and its possible that it is not defined in the actual standard, but it does work in gfortran.