So, I am using the modulus and a rand as part of a function I am writing. Now, I understand that:
rand() % 6 + 1; gives me a random number between one and six in this situation. However, I also know that
rand(); gives me a random value from 0 – 32767 and srand; changes the sequence
but I thought…
% = Whatever the remainder of a is after a / b.
… So, if you were to break rand() % 6 + 1; up, what would it look like?
I need to make sense of this for my own good because I look at rand() % 6 + 1; like this:
some random number / 6 = remainder left over from the random. Then add the one.
So, my question is two fold:
1 – how does rand() get restricted to just 1 – 5 all of a sudden instead of the spectrum of numbers from 0 – 32767?
2 – Any of those numbers (1-5) divided by 6 gives you a fractional number, not a whole one and I thought modulus only works with whole numbers. What info am I missing here?
As you can see I am confused about this. Help is always appreciated 🙂
rand()%6gives the reminder of the random number generated when divided by 6For example if
rand()generates a number 100, then the result of 100%6 is the reminder obtained when 100 is divided by 6, which is 4. So whatever the number is generated from the function rand(), when %6 is done, the output will be within 0-5(the reminder when divided by 6).“how does rand() get restricted to just 1 – 5 all of a sudden instead of the spectrum of numbers from 0 – 32767?”
rand() does not get restricted to “0-5”, it still outputs the numbers from 0 – 32767(or whatever don’t know the max limit). But when we do rand()%6, then the output will be in the range 0-5