在使用rand()函数时,每次此函数生成的值都是按固定顺序出现的。应该有一个像VB里的Randomize()函数啊,用来使随机函数每次生成的值都不同。但我不知道VC里是什么函数。那位大哥尽快告我.谢谢
使用srand()设置随机种子
srand(gettime);
srand
例如,srand( (unsigned)time( NULL ) );
问题:
你可能知道rand()返回的是虚假的随机数.默认的种子是1.你可以通过srand()来改变它.但是调用srand()就意味着你已经得到了随机数?下面的代码看上去是得到一个随机数,但是事实并非如此:
#include <stdlib.h> /* header for rand() and srand() */
#include <stdio.h> /* io header */
int main()
{
srand(rand());
for(int i=0;i<=9;i++)
printf("%d\n",rand());
return 0;
}
每运行一次,其输出都是一个结果,您可以测试一下.也就是说要是程序在每次启动需要不同的随机数,这个方法是不可行的.如何来解决?
上面提及的srand()可以改变种子的值.但是如果你将它设为常量,那么随机数列也就是常量.可以用srand(time(0))来解决.time()返回一个time_t.你可以认为它是一个整型(int),并且值是不同的.那么,我们现在可以这么写代码来实现要求:
#include <stdlib.h> /* header for rand() and srand() */
#include <stdio.h> /* io header */
#include <time.h> /* header needed for time() */
int main()
{
srand(time(0));
for(int i=0;i<=9;i++)
printf("%d\n",rand());
return 0;
}
The srand function sets the starting point for generating a series of pseudorandom integers. To reinitialize the generator, use 1 as the seed argument. Any other value for seed sets the generator to a random starting point. rand retrieves the pseudorandom numbers that are generated. Calling rand before any call to srand generates the same sequence as calling srand with seed passed as 1.
同意zhdleo(叮东)的说法,使用当前时间来作为随机数的种子比较好。
我曾经做过一个发牌机,使用的就是这种方法。
为了模拟洗牌,我使用随机数来产生牌的次序,为了发排快一些,我还使用了多线程。但是,由于两次调用发牌器的时间间隔过短,而导致随机数的种子多数一样,当然导致随机数一样,我花了很长时间才发现问题的原因,希望你能有所启发。
int 有多大,rand()生成的值就有多大。
如果你需要它在某个范围内,可以自己截取。
比如,你需要0-9之间的一个随机数,
可以进行以下操作:
srand(time(0));
int iRand = rand();
int iValue = iRand % 10;
要生成范围 a ~ b 的整数随机数,用 a + rand() % (b - a)
可以用一个外部文件来保存随机数种子。
每调用一次函数,则种子数加一。在程序开始前读入随机数种子,结束前保存。