"(rand() % 100 + 1)" - why does it give random number < 100? I started to learn c++ couple of weeks ago in my spare time. Most of codes and tutorials I do undestand, however the one mentioned above I do not get. I will appreciate any good explanation of this. Thank you :)
// random.cpp
// Outputs 20 random numbers from 1 to 100.
#include <stdlib.h>
// Prototypes of srand() and rand()
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
unsignedint
i, seed;
cout << "\nPlease type an integer between ""0 and 65535: ";
cin >> seed;
// Reads an integer.
srand( seed);
// Seeds the random
// number generator.
cout << "\n\n
""******
RANDOM NUMBERS
******\n\n";
for( i = 1 ; i <= 20 ; ++i)
cout << setw(20) << i << ". random number = "
<< setw(3) << (rand() % 100 + 1) << endl;
return 0;
}
rand() gives a random number between 0 and RAND_MAX, inclusive (RAND_MAX might be something like 65536, depending on your compiler).
rand() % 100 then takes the remainder of this number when you divide by 100 (otherwise known as "modulus"). In other words, it produces a number between [0, 99], inclusive.
For example, 124 % 100 == 24, 99 % 100 == 99, 100 % 100 == 0.
rand() % 100 + 1 takes the previous result, and adds 1 to it, giving you an range of [1, 100], inclusive.