Search code examples
c++randomnumbersgeneratorsrand

Rand() is generator the same number even though I called srand(time(NULL))


Here is my code

#include <iostream> //cout, cin
#include <time.h> // time
#include <stdlib.h> // srand(), rand()
using std::cout; //cout

int main()
{
    srand(time(NULL)); //Initializes a random seed
    int rand_number = rand() % 1 + 100; //Picks a random number between 1 and 100

    cout << rand_number << std::endl;
}

For some reason, it keeps giving me 100 when I generate the random number. Though I don't believe it should because I called srand(time(NULL)) to initialize a seed.


Solution

  • As said in the comments, rand() % 1 is nonsensical. The remainder of anything divided by 1 is 0. You then add 100 to it.

    Instead, (rand() % 100) + 1 will give you a random number in the range [1, 100].

    The facilities in <random> are much better, and it is a good idea to learn them.

    std::mt19937 mt((std::random_device()())); //create engine
    std::uniform_int_distribution<int> dist(1, 100); //define distribution
    
    dist(mt); //better random number in range [1, 100]