[求助]谁来说说随机函数的应用
小弟在网上苦找不到简单的讲解。
rand(),是产生伪随即数的函数, 但是有个缺点 :假如你分别打开同一个程序两次 , 你会发现他们产生的随即数序列是完全一样的。这是因为它们的种子是一样的。
这里牵扯到一个种子问题,如果两个程序的种子一样,那么他们产生的随即数序列是一样的。所以,一般在使用rand之前要改变种子,它的函数是:void srand( unsigned int seed );
为了使每次使用程序的种子都不一样,那么一般是使用当前的时间来作为种子。time( NULL )可以得到当前时间。
下面是个例子:
Example
/* RAND.C: This program seeds the random-number generator with the time,then displays 10 random integers. */
#include <stdlib.h>#include <stdio.h>#include <time.h>void main( void ){ int i; /* Seed the random-numbergenerator with current time so that
the numbers will be differentevery time we run. */
srand( (unsigned)time( NULL ) ); /* Display 10 numbers. */ for( i = 0; i < 10;i++ ) printf( " %6d\n", rand() );}
[此贴子已经被作者于2004-09-12 23:28:01编辑过]
