Generate random numbers from a predefined set

2

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

    
asked by anonymous 15.06.2015 / 21:23

2 answers

3
#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;
}
    
15.06.2015 / 22:11
-2

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();
    }
    
17.06.2015 / 12:27