1

这个fortran代码应该从txt文件中的简单矩阵表中复制数据,然后根据之前每行和每列的成绩计算成绩和平均值。出于某种原因,我无法打印出成绩或平均值,它们显示为空白或带有 0 或星号。该程序在从 txt 文件打印矩阵表后运行时崩溃,它说错误是访问冲突 - 所以根本没有多大帮助。到目前为止,这是我的代码:

program calculate1
real,dimension(:,:),allocatable :: a
character(200)::line
print *,'How many rows are there?'
read *,n !amount of rows
print *,'How many columns are there?'
read *,m !amount of columns
allocate (a(n+1,m+1))
open(1, file='in1.txt')
call print_out (a,n+1,m+1)
Close(1);

contains
subroutine print_out(b,n,m)
real,dimension(:,:):: b
character(200)::line(n)
character(1)::g
write(*,'(10x)',advance='no')
do j=2,m-1
write(*,100,advance='no'),'hw',j-1
enddo
100 format(a2,i2,3x)
print '(a6,a6)','exam  ','grade  '
do i=1,n-1 !makes rows from data
read(1,'(a)') line(i)  !read from in1.txt
write(*,'(a)') line(i) !write to screen
enddo
do i=1,n         !makes (m+1)th column
b(i,m+1)= sum(b(i,1:m-1))+3*b(i,m)
enddo
do j=1,m+1             !makes (n+1)th row
b(n+1,j)= sum(b(1:n,j))/n
enddo
101 format(a8,4x,20f8.2)  ! format for average print
print 101, 'averages', b(n+1,j)
endsubroutine
endprogram 

这是 in1.txt 文件中的内容:

jackson     4.    4.    4.2   8.
johnson     4.    2.    2.11  3.
sugimoto    1.    0.    1.5   0.
wong        3.5   3.    3.    2.    
4

1 回答 1

5

由于这是家庭作业,我只能提示:您的代码将文件中的一行读入字符变量并忽略它。b然后,它对尚未分配任何值的矩阵 进行一些操作。如果在 write 语句中提供了错误类型的变量,Fortran 程序通常会崩溃,例如当格式语句指定实数时的字符变量。

因为这是家庭作业:

  • 始终使用隐式无;
  • 缩进将使您的代码更易于阅读,并且更易于 SO 帮助;
  • 使用循环的矩阵求和可以更容易地使用 Fortran 的数组语法进行编程;如果您正在学习 Fortran 编程,请学习数组语法;
  • 避免全局变量和幻数,你的代码至少有其中之一。
于 2012-04-02T06:15:08.060 回答