【发布时间】:2013-11-27 06:23:34
【问题描述】:
这是Fortran: Open, form='(un)formatted', read 的后续问题。我必须创建一个数组来保存特定条件下的元素数量。
program location
implicit none
interface
function distkm(deglat1,deglon1,deglat2,deglon2)
real :: distkm
real, intent(in) :: deglat1,deglon1,deglat2,deglon2
end function distkm
end interface
integer, parameter :: maxnr = 200000
integer :: nr, i, j, ios
character(len=1) :: junkfornr
real :: start, finish
! My variable declaration
character(len=15), dimension(:), allocatable :: key
real, dimension(:), allocatable :: lat, lon
integer, dimension(:), allocatable :: jobs
! Secondary arrays
integer, dimension(:), allocatable :: jobs_within
integer, dimension(:), allocatable :: sum_jobs
! Determine total number of lines in file
nr=0
open(10, file='location_data2.txt', status='old')
do i=1,maxnr
read(10,*,iostat=ios) junkfornr
if (ios/=0) exit
if (i == maxnr) then
stop
endif
nr = nr + 1
end do
! Create variables: key, lat, lon, jobs
allocate(key(nr))
allocate(lat(nr))
allocate(lon(nr))
allocate(jobs(nr))
allocate(jobs_within(nr))
allocate(sum_jobs(nr))
rewind(10)
do i=1,nr
read(10,*) key(i), lat(i), lon(i), jobs(i)
end do
do i=1,nr
do j=1,nr
if (distkm(lat(i),lon(i),lat(j),lon(j)) <= 0.3) then
jobs_within(j) = jobs(j)
else
jobs_within(j) = 0
end if
end do
sum_jobs(i) = sum(jobs_within)
end do
close(10)
open(20,file='key_sum_jobs_0.3.txt')
do i=1,nr
write(20,100) key(i), sum_jobs(i)
end do
100 format(A15,I6)
end program location
do 循环为每个公司节省了 0.3 公里范围内的工人总数。在这里,对于每家公司,0.3 公里范围内的公司数量是不同的。如何创建一个数组(例如,n_neighbor)来记录每个公司的相邻公司数量?
编辑: 我相信以下方法可以解决问题:
do i=1,nr
n_aux(1:nr) = 0
do j=1,nr
if (distkm(lat(i),lon(i),lat(j),lon(j)) <= 1) then
jobs_within(j) = jobs(j)
n_aux(j) = n_aux(j) + 1
else
jobs_within(j) = 0
end if
end do
write(20,100) key(i), sum(jobs_within), sum(n_aux)
100 format(A15,I8,1X,I3)
end do
我创建了一个整数数组 (n_aux)。然后,unit=20 的输出文本文件保存了三列:(1)企业密钥,(2)0.3km 内的工人总数,以及(3)0.3km 内的企业数量。
需要思考的事情:
我将n_aux 的所有元素设置为0 在j 循环之前。然后,我在 if 条件成立的地方抛出 1's。是否应该有其他方式来表达这种操作,例如...动态地将值分配到数组上?
【问题讨论】: