Generate random numbers from a predefined set

Asked

Viewed 2,082 times

2

How to generate a random number in a range of non-sequential numbers. For example, a function that randomly chooses between the values, 3, 10, 20 and 2334 in the language C

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;
}

-2

You can use the Rand() function and the Srand() function, the latter serves to power Random, so that each build 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();
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.