2

Sorry, I know there are similar questions already posted but this book is confusing me nonetheless.

In "C Programming: Absolute Beginner's Guide", there is a line:

dice1 = (rand() % 5) + 1;

to generate a random number between 1 to 6 for a dice game.

Isn't this an error? From my understanding, you cannot get a remainder of 5 using % 5 so that line would only generate numbers from 1 to 5. I'm an absolute beginner so I can't tell if I'm making an error or the book is. Could someone confirm?

5areductase
  • 269
  • 2
  • 10

1 Answers1

0

Yes, 5 % 5 == 0, so you could only get numbers 1 to 5 from the full expression. The other issue with that method is that rand() probably returns numbers from 0 to 2n-1, so the total number of different values can only be divided equally to some other power of two. So the modulus doesn't give an even distribution of the resulting numbers, even assuming rand() itself gives evenly distributed values along its output range.

ilkkachu
  • 6,221
  • 16
  • 30