在 Fortran 中写出数组时控制换行符

Roe*_*oel 2 fortran

所以我有一些代码基本上可以做到这一点:

REAL, DIMENSION(31) :: month_data
INTEGER :: no_days
no_days = get_no_days()
month_data = [fill array with some values]
WRITE(1000,*) (month_data(d), d=1,no_days)
Run Code Online (Sandbox Code Playgroud)

因此,我有一个包含每个月值的数组,在循环中,我根据该月有多少天用一定数量的值填充该数组,然后将结果写入文件中。

我花了相当长的时间才理解 WRITE 的整个“一次性写出一个数组”方面,但这似乎有效。

然而,这样,它会像这样写出数组中的数字(例如 1 月,因此有 31 个值):

  0.00000         10.0000         20.0000         30.0000         40.0000         50.0000         60.0000
  70.0000         80.0000         90.0000         100.000         110.000         120.000         130.000
  140.000         150.000         160.000         170.000         180.000         190.000         200.000
  210.000         220.000         230.000         240.000         250.000         260.000         270.000
  280.000         290.000         300.000
Run Code Online (Sandbox Code Playgroud)

因此它会添加很多空格作为前缀(大概是为了让列对齐,即使数组中存在较大的值),并且它会换行以使其不超过一定的宽度(我认为是 128 个字符?不确定)。

我真的不介意额外的空格(尽管它们大大增加了我的文件大小,所以解决这个问题也很好......)但是分解线搞砸了我的其他工具。我尝试阅读几本 Fortran 手册,但虽然其中一些提到了“输出格式”,但我还没有找到一本提到换行符或列的手册。

那么,在 Fortran 中使用上述语法时如何控制数组的写出方式呢?

(另外,当我们这样做时,如何控制小数位数?我知道这些都是整数值,所以我想一起省略任何小数,但我无法将数据类型更改为由于某些原因,我的代码中出现了 INTEGER)。

jme*_*e52 6

你可能想要类似的东西

WRITE(1000,'(31(F6.0,1X))') (month_data(d), d=1,no_days)
Run Code Online (Sandbox Code Playgroud)

解释:

  • 使用*格式规范称为列表定向 I/O:它很容易编码,但您将对格式的所有控制权交给处理器。为了控制格式,您需要通过语句标签FORMAT或字符变量提供显式格式。
  • 使用F十进制形式的实数变量的编辑描述符。它们的语法是 F wd,其中w是字段的宽度,d是小数位数,包括小数点符号。 F6.0因此表示宽度为 6 个字符且没有小数位的字段。
  • 可以使用控件编辑描述符添加空格X
  • 编辑描述符的重复可以用符号前的重复次数来指示。
  • 可以使用(...创建组),并且如果前面有多次重复,则可以重复它们。
  • No more items are printed beyond the last provided variable, even if the format specifies how to print more items than the ones actually provided - so you can ask for 31 repetitions even if for some months you will only print data for 30 or 28 days.

Besides,

  • New lines could be added with the / control edit descriptor; e.g., if you wanted to print the data with 10 values per row, you could do

    WRITE(1000,'(4(10(F6.0,:,1X),/))') (month_data(d), d=1,no_days)
    
    Run Code Online (Sandbox Code Playgroud)
  • Note the : control edit descriptor in this second example: it indicates that, if there are no more items to print, nothing else should be printed - not even spaces corresponding to control edit descriptors such as X or /. While it could have been used in the previous example, it is more relevant here, in order to ensure that, if no_days is a multiple of 10, there isn't an empty line after the 3 rows of data.

  • 如果您想完全删除小数符号,则需要使用nint内在函数和 I w打印最接近的整数 (integer) descriptor:

    WRITE(1000,'(31(I6,1X))') (nint(month_data(d)), d=1,no_days)
    
    Run Code Online (Sandbox Code Playgroud)