How to generate a random number in a range of non-sequential numbers. For example, a function that randomly chooses between values, 3, 10, 20, and 2334 in the C language
How to generate a random number in a range of non-sequential numbers. For example, a function that randomly chooses between values, 3, 10, 20, and 2334 in the C language
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand(time(0)); // escolhe sequencia de numeros aleatorios
int valores[] = {3, 10, 20, 2334};
int n = sizeof valores / sizeof *valores;
printf("%d\n", valores[rand() % n]); // possible bias
return 0;
}
You can use the Rand () function and the SRand () function, the latter to feed Random, so that each compilation does not show the same value.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int gera()
{
srand( (unsigned)time(NULL) );
int val[] = { 3, 10, 20, 2334 };//Valores
int num = sizeof valores / sizeof * val;
return(valores[rand() % num]);
}
int main()
{
printf("%d",gera());
getch();
}