mardi 28 mai 2019

Clarification on calling srand

I'm wondering why it's advantageous to seed srand at the beginning of the program, instead of where I use it.

I generate pseudo-random numbers when seeding srand at the beginning of my program but I get the numbers all the same when I seed srand inside the function I call to generate the numbers

#include <iostream>
#include <ctime>
using namespace std;

int rng()
{
    const int SIZE = 10;
    int rng[10];
  srand(time(NULL));
    for (int i = 0; i < 10; i++)
    {
        rng[i] = rand() % 128 + 1;
        return rng[i];
    }

}

int main()
{
    int array;
  //srand(time(NULL)); If i put it here i get actual random numbers
    cout << "Welcome to the program";
    cout << "\nthis is your rng\n";
    for (int i = 0; i < 10; i++)
    {
        array = rng();
        cout << array << endl;
    }

    return 0;
}

When I run the program all of the numbers are the same, but when I delete the seeding from in the rng function and uncomment the srand in the main module the numbers are pseudo-random which is what I want. Im wondering why though. I've looked into it and heard that im seeding srand with a time and when I run that function the loop iterates so fast that all of the numbers are generated with the same seed value so they're all the same, but I'm wondering what's the difference from that and having srand(time(NULL)) in main because either way doesn't the function generate the numbers so fast they'll be at the same seed value anyway? It doesn't appear that way because of the different output but im curious, why?

Aucun commentaire:

Enregistrer un commentaire