dimanche 10 janvier 2021

rand() Time Issue [closed]

I'm having a bit of an issue with a rand() function. I have read up and understand that rand() and srand() are considered pseudorandom number generator but for my specific case I think this is okay; maybe I'm wrong. The problem I'm running into has to deal with the srand seed.

#include <iostream>
#include <time.h>

using namespace std;

int main()
{
    srand(time(NULL));
    int num = rand() & 101;
    for (int i = 0; i < 20; i++)
    {
        cout << num << endl;
    }
    return 0;
}

In this small snip of code, the goal is to print out random numbers between 1-100. Whenever I run this code, I get 20 printouts of the same number. Have I met a limitation of the rand() function or am I simply missing a component here? My hunch is since the seed is based off of time, I'm getting the same answer because they are all being processed within the same second. If my hunch is correct, is there a way around this so that I get 20 truly random integers?




Aucun commentaire:

Enregistrer un commentaire