mercredi 26 octobre 2022

What is the difference between using the '*' operator vs the '%' operator when using the rand() function in C++?

Below I am going to show two different versions of rand() implementations.

First, the modulo operator (%):

int r = rand() % 10;

Now, I know that this statement produces a random integer between 0-9.

Second, the multiplication operator(*):

double r = rand() * 101.0 / 100.0;

This is the one I am confused about. I have seen this implementation once before but I cannot find a good explanation of what the 'rules' are here. What are the bounds/restrictions? What is the purpose of the division instead of just typing:

double r = rand() * 1.0;



Aucun commentaire:

Enregistrer un commentaire