will this code:
int randInt = rand() % 52;
ever hit the number 52??
Printable View
will this code:
int randInt = rand() % 52;
ever hit the number 52??
No.
If you divide anything by 52, will the remainder ever be 52?
He could have. That's just a code snippet.
Wouldn't matter. The only thing the seed does is give you a "random" starting point. There's a 1/52 chance that the default seed gives you any particular number. So, assuming there really wasn't an issue with % 52 being impossible to generate 52, it would have been possible. (IE: If he had said, is there ever a chance it's 5, then yes, there is a 1/52 chance that the default seed spits out 5.)
Quzah.
ok, so then my next question is...
How can I have it spit out a random number from 1 to 52? both included...
What's the range you get from % 52?
0-51....the modulus operator is essentially saying "Whatever divided by 52 and the remainder is..." so 0-51...
Yes, we know :). I am just trying to get the OP to answer his own question step by step.
While that gives you slightly better distribution, (since RAND_MAX may not be divisible by 52), it will be VERY slow.
A far faster way would be
int r = rand() % 52 + 1;
If you don't need perfect uniformity (some values will occur very very slightly more frequently than others, most certainly undetectable for general use).
That's not any faster if you include the time used to pregenerate the random numbers :).
Have you actually tried running your code? It can take a few hours to return one value on implementations that have large RAND_MAX. Even with a minimum of 2^15 allowed by the standard, it would require ~500 calls to rand() on average to get a number in range.
rand() is a very slow function already, in most implementations.
And also, seeding the generator with current time on every call is a BAD idea. What if you make 2 calls within 1 second?