Generation of random numbers [duplicate]

0

I declare a method to generate random numbers, but the results are almost always the same, why?

int geraAleatorio(int min, int max) {

    return ((rand() % (max - min)) + min) + 1;
}

Is there any other algorithm?

    
asked by anonymous 25.02.2017 / 23:11

2 answers

1

The random seed failed to initialize. The random generator is not random indeed so you need to randomize the seed, the most common is to use the computer's clock.

You should only call srand() once in the application with the same argument. Otherwise it generates the same number.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int geraAleatorio(int min, int max) {
    return ((rand() % (max - min)) + min) + 1;
}

int main(void) {
    srand((unsigned)time(NULL));
    printf("%d\n", geraAleatorio(10, 20));
    printf("%d\n", geraAleatorio(10, 20));
    printf("%d\n", geraAleatorio(30, 40));
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
25.02.2017 / 23:20
0

Try to put this line before calling the function:

srand((unsigned) time(NULL));

Take a look at this old post will help you Random number range in C

    
25.02.2017 / 23:22