Piet
Piet

Reputation: 71

C rand() dice issue

I'm new to C and I'm reading a book about it. I just came across the rand() function. The book states that using rand() returns a random number from 0 to 32767. It also states that you can narrow the random numbers by using % (modulus operator) to do so.
Here is an example: the following expression puts a random number from 1 to 6 in the variable dice

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

I'm unable to get a remainder of 5 as any number from 0 to 33767 % 5 is equal to 0 to 4, but never 5.

Shouldn't it be % 6 in the above statement instead?

For example, if I choose randomly a number between 0 and 32767, let's say 75, then:

75 % 5 == 0
76 % 5 == 1
77 % 5 == 2
78 % 5 == 3
79 % 5 == 4
80 % 5 == 0
Etc.

So regardless of the random number between 0 and 32767, the remainder will never be 5, so it will not be possible to get a 6 number for the dice (as per the above statement).

Not sure if you will understand what I mean but your help would be much appreciated.

Upvotes: 4

Views: 902

Answers (2)

Abass Sesay
Abass Sesay

Reputation: 961

First you will have to understand how modulo (%) works. If you have say 10 and divide it by 5 you get 2 with a remainder of 0, hence the 10 % 5. The possible range of remainders you would get when you mod(modulo) 5 is 0 - 4. Remember that the possible remainders would can get when you divide by x if from 0 to x-1. So in your case with the dice program you need numbers from the range of 1 to 6 (the faces of a die) hence you would mod 6 and add 1 to this number for give the necessary shift. (rand() % 6) + 1

Upvotes: 1

taskinoor
taskinoor

Reputation: 46037

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

This will generate a random number between 1 to 5, inclusive, as you have analyzed. The % 5 in the book is probably just a typo. To get 1 to 6 it needs to be % 6.

Upvotes: 1

Related Questions