Sintaxe:
#include <cstdlib> int rand( void );
A função rand() retorna um inteiro pseudoaleatório entre 0 e RANDOM_MAX. Exemplo:
srand( time(NULL) );
for( i = 0; i < 10; i++ )
printf( "Random number #%d: %d\n", i, rand() );
Nota: Não use % (módulo) para limitar os numeros aleatórios gerados. A aleatoriedade é reduzida drasticamente. Em vez disso, use esse algoritmo para gerar uma distribuição apropriada de números aleatórios entre 0 e um outro numero:
// note the float literals are important, otherwise the integers could
// overflow when 1 is added.
int randomNumber(int hi) //the correct random number generator for [0,hi]
{
// scale in range [0,1)
const float scale = rand()/float(RAND_MAX);
return range [0,hi] return int(scale*hi + 0.5); implicit cast and truncation in return
}
Topicos Relacionados: http://www.cppreference.com/wiki/c/other/srand