Home > Net >  What is the difference between using the '*' operator vs the '%' operator when u
What is the difference between using the '*' operator vs the '%' operator when u

Time:10-27

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;

CodePudding user response:

There is no different implementations for rand() function. The difference in these two cases is the mathematical operation you do with the value returned by rand() function.

In the first case you just take the number returned by rand() and divide it to 10 using modulo operator (so getting a number between 0 to 9). And in the second case you just multiplying it by 101 (or 1).

For example rand() has returned number 123. case first: 123 % 10 gives you 3 (the reminder of the normal division). case second: you just multiply 123 by 101 which is 12423.

Checkout this.

  • Related