c - 在 C 中生成随机数

标签 c random

在搜索有关在 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/

相关文章:

c - 如何跟踪 C 程序堆区域中的内存?

python - 使用 ctypes 在共享库中免费调用

c - C 中的一个空循环。编译器是否生成了很多不必要的代码,或者我错过了什么?

javascript - 区间内的简单随机函数

Oracle聚合函数为组返回随机值?

c - 生成查找表的所有可能的二进制输入

c - 这行代码 "#define LIBINJECTION_SQLI_TOKEN_SIZE sizeof(((stoken_t*)(0))->val)"有什么作用?

具有加权概率的 Javascript 随机数

c - 尽管只调用了一次 srand(),但 rand() 重复值

python - 根据条件获取随机元素