问题描述
虽然在CI生成随机数搜索教程发现
While searching for Tutorials on generating random numbers in C I found this topic
当我尝试使用兰特()
函数不带参数,我总是得到0。当我尝试使用兰特()
带参数的功能,我总是得到值41.每当我尝试使用 arc4random()
和随机()
的功能,我得到一个错误LNK2019
When I try to use the rand()
function without parameters, I always get 0. When I try to use the rand()
function with parameters, I always get the value 41. And whenever I try to use arc4random()
and random()
functions, I get a LNK2019 error.
下面是我做了什么:
#include <stdlib.h>
int main()
{
int x;
x = rand(6);
printf("%d", x);
}
这code总是产生41.我在哪里去了?我运行Windows XP SP3和使用VS2010命令提示符进行编译。
This code always generates 41. Where am I going wrong? I'm running Windows XP SP3 and using VS2010 Command Prompt as compiler.
推荐答案
您应该呼吁兰特初始化随机数生成器之前调用srand()函数。
You should call srand() before calling rand to initialize the random number generator.
无论是与特定的种子调用它,你总是会得到相同的伪随机序列
Either call it with a specific seed, and you will always get the same pseudo-random sequence
#include <stdlib.h>
int main ()
{
srand ( 123 );
int random_number = rand();
return 0;
}
或变化的来源调用它,即时间函数
or call it with a changing sources, ie the time function
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) );
int random_number = rand();
return 0;
}
为了响应月球的评论
RAND()产生0和RAND_MAX之间的平等概率随机数(宏pre定义stdlib.h中)
In response to Moon's Commentrand() generates a random number with an equal probability between 0 and RAND_MAX (a macro pre-defined in stdlib.h)
您可以那么这个值映射到一个较小的范围,例如
You can then map this value to a smaller range, e.g.
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)
这可能足以满足大多数的用途,但它值得指出的是,在使用Mod运算符第一种情况介绍略有偏差,如果N不均匀地分成RAND_MAX + 1。
This might be sufficient for most uses, but its worth pointing out that in the first case using the mod operator introduces a slight bias if N does not divide evenly into RAND_MAX+1.
随机数生成器是有趣的,复杂的,它被广泛地说,在C标准库中的RAND()生成器是不是一个伟大的品质随机数生成器,读取(http://en.wikipedia.org/wiki/Random_number_generation对质量的定义)。
Random number generators are interesting and complex, it is widely said that the rand() generator in the C standard library is not a great quality random number generator, read (http://en.wikipedia.org/wiki/Random_number_generation for a definition of quality).
http://en.wikipedia.org/wiki/Mersenne_twister (来源http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html )是一种流行的高品质的随机数发生器。
http://en.wikipedia.org/wiki/Mersenne_twister (source http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html ) is a popular high quality random number generator.
另外,我不知道arc4rand()或随机(的),所以我不能发表评论。
Also, I am not aware of arc4rand() or random() so I cannot comment.
这篇关于生成用C随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!