mardi 17 avril 2018

Why 1+rand()%6 is wrong?

When reading how to use std::rand, I found this code on cppreference.com

// Dice simulation
int x = 7;
while(x > 6) 
        x = 1 + std::rand()/((RAND_MAX + 1u)/6);  // Note: 1+rand()%6 is wrong!

What is wrong with the expression at right? Tried it and it works perfectly.




Aucun commentaire:

Enregistrer un commentaire