有哪个Fortran高手指点一下为什么调试程序出错

[复制链接]
查看11 | 回复1 | 2011-3-13 12:52:38 | 显示全部楼层 |阅读模式
module a

implicit none

integer,allocatable::spin(:)

integer::M,l

end module a







program test

use a

implicit none

integer::i,n

real ::harvest

M=0

print *,\'input the length of the lain\'

read *,l

allocate (spin(l))

call random_number(harvest)

do i=1,l

n=int(l*harvest)

if(harvestl/2)then

spin(i)=1

else

spin(i)=-1

endif

enddo

call calculate_magnet

print \'(a,i5)\',\'the magnet of the lain is \',M



contains



subroutine calculate_magnet

use a

implicit none

allocate(spin(l))

do i=1,l

M=M spin(i)

enddo

end subroutine calculate_magnet

end program test
回复

使用道具 举报

千问 | 2011-3-13 12:52:38 | 显示全部楼层
<pre id=\"best-answer-content\" class=\"reply-text mb10\">注释掉子函数calculate_magnet中的allocate(spin(l)),因为这是重复分配。
同时在主函数中加入deallocate(spin),避免内存泄漏。
程序如下:

module a

implicit none

integer,allocatable::spin(:)

integer::M,l
end module a

program test

use a

implicit none

integer::i,n

real ::harvest

M=0

print *,\'input the length of the lain\'

read *,l

allocate (spin(l))

call random_number(harvest)

do i=1,l

n=int(l*harvest)

if(harvestl/2)then

spin(i)=1

else

spin(i)=-1

end if

end do

call calculate_magnet

print \'(a,i5)\',\'the magnet of the lain is \',M

deallocate(spin)
contains


subroutine calculate_magnet

use a

implicit none
!
allocate(spin(l))

do i=1,l

M=M spin(i)

end do

end subroutine calculate_magnet
end program test
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行