gpt4 book ai didi

c - 是否允许 srand(0) 具有与 srand(1) 相同的效果?

转载 作者:行者123 更新时间:2023-12-05 08:45:07 25 4
gpt4 key购买 nike

是否允许 srand(0)srand(1) 具有相同的效果?

C11, 7.22.2.2 srand 函数(强调):

The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand.

但是,在 glibc srand(0) 中有 the same effect作为 srand(1):

  /* We must make sure the seed is not 0.  Take arbitrarily 1 in this case.  */
if (seed == 0)
seed = 1;

因此,same sequence后续调用 rand 返回伪随机数,这令人困惑。

额外:我们​​看到在 MSVC 中 srand(0)srand(1) 没有相同的效果。

最佳答案

Is it allowed for srand(0) to have the same effect as srand(1)?

您从语言规范中引用的文本没有其他说明,我也没有任何其他理由认为不是。你强调了“新序列”这个词,但这绝不意味着不同的种子必须产生不同的序列。

事实上,您引用的描述绝不会以提供给 srand() 的 key 值作为后续 PRN 序列的新颖性的条件。考虑这个函数,然后:

void rtest(void) {
srand(42);
int x1 = rand();
srand(42);
int x2 = rand();
if (x1 == x2) {
puts("equal");
} else {
puts("unequal");
}
}

我希望该函数的执行打印“相等”,更一般地说,在第一个 srand() 之后生成的任意数量的 PRN 将等于在之后生成的相同数量的 PRN第二。那么,在什么意义上,第二个 srand() 调用履行了为 PRN 序列使用指定 key 的义务?

"new"应该理解为停止使用当前的伪随机数序列,并从一开始就开始使用以指定种子为特征的序列,而不管哪个序列那是。不要求不同的键代表不同的序列,尽管这会影响实现的感知质量。

关于c - 是否允许 srand(0) 具有与 srand(1) 相同的效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74193216/

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