logo

rand() en C

La función rand() en el lenguaje de programación C se utiliza para generar números pseudoaleatorios. Se utiliza en C para generar números aleatorios en el rango de 0 a RAND_MAX.

La función rand() es parte de la biblioteca C estándar entonces, para usar esta función, necesitamos incluir la biblioteca.



Sintaxis de rand()

int rand (void)>

Parámetros

  • Esta función no toma ningún parámetro.

Valor de retorno

  • Esta función devuelve el valor entre 0 y RAND_MAX donde RAND_MAX es la macro que está definida en la biblioteca.

Nota: La función rand() de forma predeterminada utiliza el valor 1 como semilla para generar números aleatorios, lo que conduce a la generación de la misma secuencia de números aleatorios. Para evitar esto podemos utilizar señor() función para especificar una nueva semilla para la función rand().

Ejemplos de rand() en C

Ejemplo 1: Ilustración de la función rand()

C








// C program to illustrate the use of rand() function> #include> #include> > int> main()> {> >// Generate a random number using the rand() function> >int> value =>rand>();> > >// Print the generated random value> >printf>(>'The Random Value is: %d'>, value);> > >return> 0;> }>

>

>

Producción

The Random Value is: 1804289383>

Complejidad del tiempo :O(1)
Complejidad espacial: O(1)

Ejemplo 2: generar 10 números aleatorios

C




// C program to generate 10 random number using rand()> // function> #include> #include> > int> main()> {> >int> i = 0;> >// Loop through 10 times> >for> (; i <10; i++) {> >// Generate a random number using the rand()> >// function> >int> value =>rand>();> > >// Print the generated random value> >printf>(>'%d '>, value);> >}> > >return> 0;> }>

>

>

Producción

1804289383 846930886 1681692777 1714636915 1957747793 424238335 719885386 1649760492 596516649 1189641421>

Pero, si queremos generar algunos números aleatorios en el rango de 0 a N, entonces debemos modificar imprimiendo el módulo de (N+1) de los números generados por la función rand().

Ejemplo: generar números aleatorios menores que N

C




// C program to generate random numbers smaller than a> // particular number n> #include> #include> int> main()> {> >// Set a constant 'N' to 1000> >int> N = 1000;> > >// Loop through 10 times> >for> (>int> i = 0; i <10; i++) {> >// Generate a random number between 0 and N using> >// the rand() function> >int> value =>rand>() % (N + 1);> >// Print the generated random value> >printf>(>'%d '>, value);> >}> > >return> 0;> }>

>

>

Producción

897 802 765 992 1 521 220 380 729 969>

De esta manera, podemos generar fácilmente el número aleatorio de 0 a N.

Además, si queremos un número aleatorio que existirá entre un límite inferior y límite_superior , podemos hacer esto usando matemáticas simples en el número aleatorio generado por la función rand().

Ejemplo: generar números aleatorios dentro de un rango

C




// C program to illustrate how to generate random number> // withing a range> #include> #include> int> main()> {> >// Set the upper bound for random numbers> >int> upper_bound = 1000;> >// Set the lower bound for random numbers> >int> lower_bound = 100;> > >// Loop through 10 times> >for> (>int> i = 0; i <10; i++) {> >// Generate a random number within the specified> >// bounds> >int> value =>rand>() % (upper_bound - lower_bound + 1)> >+ lower_bound;> >// Print the generated random value> >printf>(>'%d '>, value);> >}> > >return> 0;> }>

Linux editar un archivo
>

>

Producción

943 897 704 678 132 783 902 760 689 765>