【问题标题】:Writing a Matrix Array of 2 Rows by 3 Columns, To an Output Text File in Fortran 95将 2 行 3 列的矩阵数组写入 Fortran 95 中的输出文本文件
【发布时间】:2019-08-10 20:51:39
【问题描述】:

我目前正在学习如何编写矩阵数组以在 Fortran 95 中输出文本文件。我面临的问题是,我正在处理的 2 行乘 3 列的矩阵数组没有格式化为我希望在输出文本文件中。我相信,我缺少一两行代码,或者没有在我拥有的当前代码行中添加一些代码。下面是我的代码行、当前输出数据和所需输出数据。目标是获得“所需的输出数据”。请告诉我我的错误,我缺少哪些代码/代码行以及我应该在哪里添加代码/代码行。每个答案都受到欢迎和赞赏。谢谢 Stackovites。

代码行数:

Program Format2
!illustrates formatting Your Output
Implicit None
Integer:: B(2,3)
Integer:: k,j
!Open Output Text File at Machine 8
Open(8,file="formatoutput2.txt")
Data B/1,3,5,2,4,6/
Do k= 1,2
  B(2,3)= k
!Write to File at Machine 8 and show the formatting in Label 11
Write(8,11) B(2,3)
11 format(3i3)
    End Do
  Do j= 3,6
    B(2,3)= j
!Write to File at Machine 8 and show the formatting in Label 12
Write(8,12) B(2,3)
12 format(3i3)
End Do
End Program Format2

当前输出数据

  1
  2                                        
  3                                      
  4                                         
  5
  6

所需的输出数据

1  3  5
2  4  6

【问题讨论】:

  • 在每一行,您都为B(2,3) 赋值(因此不要使用数组)并一次写入一个元素B(2,3)。您可以使用您的格式编写 3 个整数的步幅,但实际上并不给它三个整数。使用适当的矢量元素将您的文字分成两行。
  • 如果您正在学习使用 Fortran 编程,请不要学习 DATA 并尝试使用格式字符串而不是标记为 FORMAT 的语句。一定要学习适当的缩进,以便结构清晰。

标签: fortran gfortran fortran90 intel-fortran fortran95


【解决方案1】:

我已经看到了我的错误。我给 Fortran 编译器的指令是我在我的输出文本文件中得到的结果。我声明了两两行(1,2)和(3,4,5,6);而不是声明 (1,2) 的 3-3 列; (3,4) 和 (5,6)。下面是获取所需输出数据的正确代码行。

Lines of Codes:

Program Format2

!illustrates formatting Your Output

Implicit None

Integer:: B(2,3)

Integer:: k,j

!Open Output Text File at Machine 8

Open(8,file="formatoutput2.txt")

Data B/1,2,3,4,5,6/

!(a)Declare The 1st Two-2 Values You want for k Two-2 Rows, that is (1 and 2)

!(b)Note, doing (a), automatically declares the values in Column 1, that is (1 and 2)

Do k= 1,2

  B(2,3)= k

    End Do

!(c)Next, Declare, the Four Values You want in Column 2 and Column 3. That is [3,4,5,6]

!(d) Based on (c), We want 3 and 4 in "Column 2"; while "Column 3", gets 5 and 6.

Do j= 3,6

 B(2,3)= j

 End Do

!Write to File at Machine 8 and show the formatting in Label 13

Write(8,13) ((B(k,j),j= 1,3),k= 1,2)

13 format(3i3)

End Program Format2

The Above Lines of Codes, gives the Desired Output below:

1   3   5

2   4   6

【讨论】:

  • 这段代码很奇怪。作为一个实验:删除两个do 循环,重新编译,重新运行,看看会发生什么。
【解决方案2】:

B(2,3) 仅指数组的一个特定元素。即第一个维度中索引为 2 且另一维度中索引为 3 的元素。要引用不同的元素,请使用B(i,j),其中ij 是具有所需索引的整数。要引用整个数组,请仅使用 BB(:,:) 来表示包含整个数组的数组部分。

所以要设置值

do j = 1, 3
  do i = 1, 2
    B(i,j) = i + (j-1) * 2
  end do
end do

并使用本网站上无数重复中显示的方法之一(Print a Fortran 2D array as a matrixWrite matrix with FortranHow to write the formatted matrix in a lines with fortran77?Output as a matrix in fortran - 搜索更多,会有更好的...)在此站点上打印它们

do i = 1, 2
   write(8,'(999i3)') B(i,:)
end do

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 2015-06-01
    • 1970-01-01
    • 2021-03-14
    • 2015-02-16
    • 1970-01-01
    • 2013-02-06
    相关资源
    最近更新 更多