gpt4 book ai didi

php - rand() 在 php 中是否依赖于时间?

转载 作者:可可西里 更新时间:2023-11-01 13:41:46 24 4
gpt4 key购买 nike

让我们解释一下我的意思。

前段时间,在用c#写程序时,犯了如下错误:

int Randomize()
{
Random r=new Random();
return r.Next(0,10);
}

在 C# 中,这是一个错误,因为连续多次调用此函数将返回相同的值。这是因为 Random 构造函数使用时间种子,并且调用之间的时间差太小(我花了一个小时才找到那个 :))。

现在我在 php 中使用 rand(...),我需要输出始终不同,即使同时执行 2 个脚本也是如此。

我是否必须做某事才能获得此结果,或者它是否设计为以这种方式工作?

最佳答案

rand()mt_rand() 调用 srand()mt_srand() 来生成总是随机的结果。但是在 php.net 上有一篇有趣的帖子:

Note that the automatic seeding seems to be done with the current number of seconds which means you can get the same results for several runs on a fast server. Either call srand() yourself with a more frequently changing seed or use mt_rand() which doesn't appear to suffer from the problem.

因此,只需更频繁地调用srandmt_rand

关于php - rand() 在 php 中是否依赖于时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11203770/

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