0
so naturally rand() % X goes from 0 -> X-1?
3 Respuestas
+ 1
Yes of course, that's the use of modulo
+ 1
Yes. % gives you the remainder of the euclidian division.
A note about % in C++: in (n%m), if n is negative, (n%m) will be between -(m-1) and 0 instead. This is not an issue here because rand() always returns a positive number. But if n can take negative values and you want the result of (n%m) to always be positive, you can use ((n%m + m)%m) as a workaround for example.
Another note: when using (rand()%m), the results are slightly biaised towards early numbers unless m is a power of two. This is not much of an issue if m is small and you want the random numbers for non-sensitive stuff. Otherwise, you can use ((m*rand())/(RAND_MAX + 1.0)).
0
yes