Oharra
Orrialde honetara sartzeak baimena behar du. Saioa hasteko edo direktorioak aldatzen saia zaitezke.
Orrialde honetara sartzeak baimena behar du. Direktorioak aldatzen saia zaitezke.
Genera un número pseudoaleatorio. Existe una versión más segura mediante programación disponible de esta función; vea rand_s. Los números generados por rand no son criptográficamente seguros. Para una generación de números aleatorios más segura criptográficamente, use rand_s o las funciones declaradas en la biblioteca estándar de C++ en <random>.
Sintaxis
int rand(void);
Valor devuelto
rand devuelve un número pseudoaleatorio, como se describe arriba. No se devuelve ningún error.
Comentarios
La función rand devuelve un entero pseudoaleatorio comprendido entre 0 y RAND_MAX (32767). Use la función srand para inicializar el generador de números pseudoaleatorios antes de llamar a rand.
La función rand genera una secuencia conocida y no es adecuada para su uso como función criptográfica. Para una generación de números aleatorios más segura criptográficamente, use rand_s o las funciones declaradas en la biblioteca estándar de C++ en <random>.
De manera predeterminada, el estado global de esta función está limitado a la aplicación. Para cambiar este comportamiento, consulte Estado global en CRT.
Requisitos
| Routine | Encabezado necesario |
|---|---|
rand |
<stdlib.h> |
Para obtener más información sobre compatibilidad, consulte Compatibilidad.
Ejemplo
// crt_rand.c
// This program seeds the random-number generator
// with a fixed seed, then exercises the rand function
// to demonstrate generating random numbers, and
// random numbers in a specified range.
#include <stdlib.h> // rand(), srand()
#include <stdio.h> // printf()
void SimpleRandDemo(int n)
{
// Print n random numbers.
for (int i = 0; i < n; i++)
{
printf(" %6d\n", rand());
}
}
void RangedRandDemo(int range_min, int range_max, int n)
{
// Generate random numbers in the interval [range_min, range_max], inclusive.
for (int i = 0; i < n; i++)
{
// Note: This method of generating random numbers in a range isn't suitable for
// applications that require high quality random numbers.
// rand() has a small output range [0,32767], making it unsuitable for
// generating random numbers across a large range using the method below.
// The approach below also may result in a non-uniform distribution.
// More robust random number functionality is available in the C++ <random> header.
// See https://learn.microsoft.com/cpp/standard-library/random
int r = ((double)rand() / RAND_MAX) * (range_max - range_min) + range_min;
printf(" %6d\n", r);
}
}
int main(void)
{
// Seed the random-number generator with a fixed seed so that
// the numbers will be the same every time we run.
srand(1792);
printf("Simple random number demo ====\n\n");
SimpleRandDemo(10);
printf("\nRandom number in a range demo ====\n\n");
RangedRandDemo(-100, 100, 100000);
}```
```Output
Simple random number demo ====
5890
1279
19497
1207
11420
3377
15317
29489
9716
23323
Random number in a range demo ====
-82
-46
50
77
-47
32
76
-13
-58
90
Vea también
Compatibilidad con cálculos matemáticos y el punto flotante
srand
rand_s
Biblioteca <random> de C++