dimanche 12 février 2023

Why not use Math.round instead of Math.floor?

I am making a simple exercise in JavaScript in which I have to generate a random number between 1 and 3 in JavaScript and found this:

return Math.floor(Math.random() * (max - min + 1) + min);

But with a friend we figured out that we can use Math.round instead for the same purpose:

return Math.round(Math.random() * (max - min) + min);

What caught our attention is that the last formula is not being suggested anywhere on Internet (as far as we were able to search for it...).

Are there any explanation about why this is not used?

We have tried to confirm why return Math.round(Math.random() * (max - min) + min); is not being suggested for the use of generating random numbers instead/or as an alternative to return Math.round(Math.random() * (max - min) + min);




Aucun commentaire:

Enregistrer un commentaire