当编译器说
错误:“random_seed”内在函数的“put”参数大小太小
这意味着你的变量的大小seed
太小。
在这种情况下你有seed
大小为 4(我猜编译器肯定期望(至少)为 12)。
数组的大小必须具有一定的大小,这取决于编译器。您可以通过调用来确定所需的大小random_seed
与另一个论点
integer seed_size
integer, allocatable :: seed(:)
call random_seed(size=seed_size)
allocate(seed(seed_size))
seed = ...
call random_seed(put=seed)
正如 Vladimir F 在评论中指出的那样,gfortran 文档本身有一个例子这种方法。
如果您不关心可移植性,则可以仅使用大小为 12 的数组以及您选择的值。
作为更高级的阅读,我会说另一件事。我上面给出的示例确实与您的代码不太可比。也就是说,您说种子设置子例程的输入保证大小至少为 4,并且它可能包含也可能不包含您想要用作种子的值。
正如我上面提到的,您可以将其更改为 12,但这不可移植。如果你想便携,事情就会变得更加尴尬。
integer, dimension(4), intent(inout):: seed
有一个大小为 4 的显式形状数组作为虚拟参数。主程序中的实际参数是一个至少具有该大小的数组。然而,这个尺寸是一个规范表达而且,唉,call random_seed(size=seed_size)
没有给我们一些可以在规范表达式中使用的东西。
也许像
subroutine setSEED (seed)
integer, allocatable, intent(inout) :: seed(:)
integer seed_size
! Determine the correct size for the seed
call random_seed(size=seed_size)
! If our seed isn't set, or is too small, kill it.
if (ALLOCATED(seed)) then
if (SIZE(seed)<seed_size.or.seed(LBOUND(seed,1))==0.) deallocate(seed)
end if
! If seed isn't allocated (perhaps we killed it because it was too small)
! then allocate it to the correct size and initialize it.
if (.not.ALLOCATED(seed)) then
allocate(seed(seed_size))
seed = ... ! Our fallback seed initialization
end if
! Finally, put the seed. Using one we set, or the one originally given.
call random_seed(put=seed)
end subroutine
当然,这要求实际论证是allocatable
,但如果您正在处理便携式播种机,那是一件好事。