0

so naturally rand() % X goes from 0 -> X-1?

14th Oct 2016, 5:22 AM
lucas
3 Respostas
+ 1
Yes of course, that's the use of modulo
14th Oct 2016, 8:10 AM
Venkatesh(Venki)
Venkatesh(Venki) - avatar
+ 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)).
14th Oct 2016, 10:49 AM
Zen
Zen - avatar
0
yes
14th Oct 2016, 6:41 AM
marcram