C++ and rand()
February 17, 2009 10:55 AM
Subscribe
C++ and the rand() function. Please explain why this piece of code works the way it does:
cout << rand() % 20 << endl;
srand(time(0));
cout << rand() % 20 << endl;
This returns a random number between 0 and 20, as promised by the book I'm reading as well as internet tutorials.
If I remove "% 20" from the code and am left with
srand(time(0));
cout << rand() << endl;
This returns a really big number like 1847292034.
Looking at the code, I would think that adding "% 20" should do nothing more than divide a random number like 1847292034 by 20 and return the integer portion (92364601). But instead the compiler parses it in a different way that says not to generate a random number larger than 20.
Am I interpreting this wrong? Why does the compiler interpret this as something other than a mathematical operation? Is this type of thing common in C++?
Thanks!
(I'm using g++ to compile on a Ubuntu system.)
posted by Ziggy Zaga to computers & internet (13 comments total)
% is the modulus operator. It does not return the integer portion of the division operation, but the "remainder".
17/20 = 0, remainder 17
17%20 = 17
23/20 = 1, remainder 3
23%20 = 3
posted by phrakture at 10:57 AM on February 17