2016-07-14 82 views
1

我在下面有一個簡單的Fortran代碼,我從文本文件中讀取矩陣,然後將它傳遞給子例程。但是當它在子程序中讀取時,它會給出一個垃圾值。我似乎無法弄清楚代碼有什麼問題?如何在Fortran中讀取/寫入矩陣?

program main 
implicit none 
real, dimension(:,:), allocatable :: mat 
open (unit=99, file='inp.txt', status='old', action='read') 
allocate(mat(2,2)) 
read(99, *), mat 
CALL fun(mat) 
end 

subroutine fun(mat) 
dimension mat(2,2) 
write(*,*) mat 
return 
end 

矩陣mat被讀入作爲[2 4; 2 10],但是當該子程序內顯示它給出了[1073741824 1082130432; 1073741824 1092616192]

+1

你的墊有一個隱式類型的整數,但你傳遞它的實數...更好地使用模塊和隱含在無處... – haraldkl

+0

謝謝。在子程序中包含'Implicit none'並聲明mat爲'real'! – Jay

回答

2

如果你的Fortran使用隱式變量聲明,變量開始IJKLM,或N表示整數(默認情況下)。

由於在主程序的範圍內只有implicit none,但子程序不能,因此real數組mat被解釋爲子程序中的整數。因此,垃圾。

只需在子例程中聲明matreal即可解決您的問題。