使用rand函數(shù)獲得隨機(jī)數(shù)。rand函數(shù)返回的隨機(jī)數(shù)在0-RAND_MAX(32767)之間。
例子:
/* 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-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );
/* Display 10 numbers. */
for( i = 0; i < 10;i++ )
printf( " %6d\n", rand() );
}
在調(diào)用這個(gè)函數(shù)前,最好先調(diào)用srand函數(shù),如srand( (unsigned)time( NULL ) ),這樣可以每次產(chǎn)生的隨機(jī)數(shù)序列不同。
如果要實(shí)現(xiàn)類似0-1之間的函數(shù),可以如下:
double randf()
{
return (double)(rand()/(double)RAND_MAX);
}
如果要實(shí)現(xiàn)類似Turbo C的random函數(shù),可以如下:
int random(int number)
{
return (int)(number/(float)RAND_MAX * rand());
}