首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Fortran 95中将2行x 3列的矩阵数组写入输出文本文件

在Fortran 95中,可以使用以下代码将2行x 3列的矩阵数组写入输出文本文件:

代码语言:txt
复制
program write_matrix
  implicit none
  
  integer, parameter :: rows = 2
  integer, parameter :: cols = 3
  real :: matrix(rows, cols) = reshape([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [rows, cols])
  integer :: i, j
  character(len=20) :: filename = "output.txt"
  integer, parameter :: status = 0
  integer :: unit
  
  ! Open the file for writing
  open(newunit=unit, file=filename, status='replace', action='write', iostat=status)
  
  if (status /= 0) then
    write(*, *) "Error opening the file"
    stop
  end if
  
  ! Write the matrix to the file
  do i = 1, rows
    do j = 1, cols
      write(unit, '(f8.2)') matrix(i, j)
    end do
    write(unit, *)
  end do
  
  ! Close the file
  close(unit)
  
  write(*, *) "Matrix written to", trim(filename)
  
end program write_matrix

上述代码中,我们首先定义了一个2行x 3列的实数矩阵数组matrix,并将其初始化为[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]。然后,我们指定了输出文本文件的文件名filename为"output.txt"。

接下来,我们使用open语句打开文件,其中newunit=unit表示为文件分配一个新的逻辑单元号,file=filename表示打开的文件名,status='replace'表示如果文件已存在则替换,action='write'表示以写入模式打开文件,iostat=status表示将打开文件的状态保存在status变量中。

然后,我们使用嵌套的do循环遍历矩阵的每个元素,并使用write语句将每个元素写入文件。'(f8.2)'是一个格式说明符,表示将实数以8个字符的宽度和2位小数的精度写入文件。在每行的末尾,我们使用write(unit, *)语句写入一个空行。

最后,我们使用close语句关闭文件,并输出一条消息指示矩阵已写入文件。

请注意,上述代码中的文件操作是使用Fortran的内置文件处理功能完成的,没有涉及到特定的云计算品牌商的产品。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券