Aleatorio#
Introducción#
La biblioteca estándar de C++ proporciona funciones para generar números pseudoaleatorios. Estas se pueden usar en VEXcode IQ para comportamientos que requieren variabilidad o azar.
Funciones#
The <cstdlib> library includes the following functions:
rand#
Devuelve un número entero aleatorio entre 0 y 2.147.483.647.
Available Functionsint rand();
Esta función no acepta ningún parámetro.
Return ValuesDevuelve un número entero aleatorio entre 0 y 32767.
NotesTo return a random integer within an exclusive limit, use the pattern
rand() % max.To return a random integer within a specific range, use the pattern
rand() % (max - min + 1) + min.
// Display a random number
Brain.Screen.print("%d", rand());
// Display a random number between 0 and 100
Brain.Screen.print("%d", rand() % 101);
// Display a random number between 5 and 10
Brain.Screen.print("%d", rand() % (10 - 5 + 1) + 5);
srand#
Sets the seed to be used by the pseudo-random number generator in the rand function.
void srand( unsigned int seed );
Parámetro |
Tipo |
Descripción |
|---|---|---|
|
|
El valor inicial de la semilla. |
Esta función no devuelve ningún valor.
NotesCall
srandonly once, near the start of your project, before callingrand. You do not need to call it before everyrand.If
srandis never called, the program behaves as ifsrand(1)was used. This meansrandproduces the same sequence of numbers every time the project runs.Para obtener resultados diferentes cada vez que se ejecute el proyecto, inicialice con un valor que cambie entre ejecuciones, como el temporizador de Brain.
To get the same results every time (useful for testing), seed with a fixed number such as
srand(1).
// Use the same seed for random number
srand(5);
Brain.Screen.print("%d", rand() % 100);