gpt4 book ai didi

c - 在 C 中生成随机数

转载 作者:太空狗 更新时间:2023-10-29 16:39:17 25 4
gpt4 key购买 nike

在搜索有关在 C 中生成随机数的教程时,我找到了 this topic

当我尝试使用不带参数的 rand() 函数时,我总是得到 0。当我尝试使用带参数的 rand() 函数时,我总是得到得到值 41。每当我尝试使用 arc4random()random() 函数时,我都会收到 LNK2019 错误。

这是我所做的:

#include <stdlib.h>
int main()
{
int x;
x = rand(6);
printf("%d", x);
}

此代码始终生成 41。我哪里出错了?我正在运行 Windows XP SP3 并使用 VS2010 命令提示符作为编译器。

最佳答案

在调用 rand 初始化随机数生成器之前,您应该先调用 srand()。

要么用特定的种子调用它,你总是会得到相同的伪随机序列

#include <stdlib.h>

int main ()
{
srand ( 123 );
int random_number = rand();
return 0;
}

或者用变化的来源调用它,即时间函数

#include <stdlib.h>
#include <time.h>

int main ()
{
srand ( time(NULL) );
int random_number = rand();
return 0;
}

回应 Moon 的评论rand() 生成一个等概率随机数,介于 0 和 RAND_MAX 之间(stdlib.h 中预定义的宏)

然后您可以将此值映射到较小的范围,例如

int random_value = rand(); //between 0 and RAND_MAX

//you can mod the result
int N = 33;
int rand_capped = random_value % N; //between 0 and 32
int S = 50;
int rand_range = rand_capped + S; //between 50 and 82

//you can convert it to a float
float unit_random = random_value / (float) RAND_MAX; //between 0 and 1 (floating point)

这对于大多数用途来说可能就足够了,但值得指出的是,在第一种情况下,如果 N 不能均匀地划分为 RAND_MAX+1,则使用 mod 运算符会引入轻微的偏差。

随机数生成器既有趣又复杂,人们普遍认为 C 标准库中的 rand() 生成器不是质量很好的随机数生成器,请阅读(http://en.wikipedia.org/wiki/Random_number_generation 以了解质量的定义)。

http://en.wikipedia.org/wiki/Mersenne_twister (来源 http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html)是一种流行的高质量随机数生成器。

此外,我不知道 arc4rand() 或 random(),所以我无法发表评论。

关于c - 在 C 中生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3067364/

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