gpt4 book ai didi

fortran - 在 Fortran 中读取行数未知的文件

转载 作者:行者123 更新时间:2023-12-02 03:55:04 26 4
gpt4 key购买 nike

英雄我使用的新代码。我试过这个,如果我先声明它就可以工作,这不是我想要的。我需要知道总行数(n) 然后在我的模拟中使用该数字。但是,在变量声明中,我需要在读取数据之前减少 xy(n),如果这样做,代码将不会运行。

数据文件是两列随机模拟的正常数据

让我们这样说

1  3
2 4
3 6
4 8
5 9
6 8
7 1
8 9
99 88

我尝试了以下代码来确定 n 但它没有用!

     program reading

implicit none
integer,allocatable :: a(:,:)
integer :: pair(2)
integer :: unit, n, io,k
!!!variable declaration

real, dimension(1:n)::x,y
integer:: T, I1, I2, I3, i, j, dist
open(2, file = 'xyBVNData_R.txt', status = 'old', action = 'read')


n = 0
DO
READ(2,*,iostat=io)
IF (io/=0) EXIT
n = n + 1
END DO
CLOSE (2)
print*, n



DO i=1,n!!!
DO j=1,n!!
dist=0.0
DIST = dist+(sqrt((x(i)-x(j))**2 + (y(i)-y(j))**2))

ENDDO
ENDDO

!!! writing and saving
Do i= 1, n
write(*,*) i, x(i)
ENDDO
end program reading

最佳答案

您不能声明具有未知维度“dimension(1:n)”的变量。

此程序首先读取文件以确定行数:

program reading
implicit none
! variable declaration
real, dimension(:) ,allocatable :: x ,y
real :: dist
integer:: i, j ,n ,io

open(2, file = 'xyBVNData_R.txt', status = 'old', action = 'read')

n = 0
DO
READ(2,*,iostat=io)
IF (io/=0) EXIT
n = n + 1
END DO
print*, n

allocate( x(n) ,y(n) )
rewind(2)
DO i =1,n
READ(2,*) x(i),y(i)
END DO

dist=0.0
DO i=1,n
DO j=1,n
dist = dist + sqrt( (x(i)-x(j))**2 + (y(i)-y(j))**2 )
END DO
END DO

! writing and saving
DO i= 1, n
write(*,*) i, x(i)
END DO

end program reading

另一种选择(Fortran 2003),它通过在读取新行时添加新元素来重新分配数组 xy:

program reading
implicit none
! variable declaration
real, dimension(:) ,allocatable :: x ,y
real :: dist ,x_tmp ,y_tmp
integer:: i, j ,n ,io

open(2, file = 'xyBVNData_R.txt', status = 'old', action = 'read')

n = 0
allocate( x(0) ,y(0) )
DO
READ(2,*,iostat=io) x_tmp,y_tmp
x = [x,x_tmp]
y = [y,y_tmp]
IF (io/=0) EXIT
n = n + 1
END DO
print*, n

dist=0.0
DO i=1,n
DO j=1,n
dist = dist + sqrt( (x(i)-x(j))**2 + (y(i)-y(j))**2 )
END DO
END DO

! writing and saving
DO i= 1, n
write(*,*) i, x(i)
END DO

end program reading

关于fortran - 在 Fortran 中读取行数未知的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44256136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com