dimanche 13 janvier 2019

C++ - rand() Generates The Same Number Always

I am working on my first Arduino project, I code in Java, JavaScript, Python, but C++ seems to be very different, it takes multi lines of code just to generate a random number, and even that it does not seem to be working with me. Code:

const char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // List of all possible hex chars.
srand(time(NULL)); //initialize the random seed.
int randomNum = rand() % (sizeof(hexChars)/sizeof(hexChars[0])); //Generates a random number between 0 and 15.
return hexChars[randomNum];

This should return a new random number each time I run the program, because I initialized a random seed based on time, but the random number is always 2.

What is the problem? How to solve it?




Aucun commentaire:

Enregistrer un commentaire