thisguy
thisguy

Reputation: 1

Why does C use modulus for random numbers?

C:

rand() % (max - min) 

Let's say the random is between 0-10..

rand() % 10

0.567 % 10 = that same number. (0.567). It isn't really doing anything. a rand() is always between 0-1, and as long as max-min is always >= 1, it will do nothing at all.

Wouldn't you just use multiplication instead of modulo?

int rand = rand() * (max - min) + 1

Upvotes: 0

Views: 705

Answers (1)

Ranic
Ranic

Reputation: 486

rand() returns a number between 0 and RAND_MAX. You would then use modulo to constrain it to a certain range. So if you wanted a number between 0 and 10, you would do rand() % 10.

Upvotes: 5

Related Questions