0
#include <iostream>
#include <ctime>
#include <cstdlib>

 using namespace std;

 int random_Number();
 int random_One();

 int main(){
     cout << "You have : " << random_Number() << endl;
    cout << "The dealer has : " << random_Number() << endl;
}


int random_Number(){
    int v1, v2;
    srand((unsigned)time(NULL));
    v1 = rand() % 10 + 1;
    v2 = rand() % 10 + 1;
    return v1 + v2;
}

If I understand correctly, srand() is a seed which will change each time I run the program since the time changes and therefore so does srand(). However, since time does not change once the program has been started, the program will keep using the same seed and thus generating the same numbers over and over.

So, if I want my function random_Number to generate a new random number every time it is called, then I must also change the seed. I assume you need to set your seed to something else than time, but I don't know what else? It's a bit paradoxical that you can't loop the seed, since that would require a random number for each iteration - which is exactly the problem I have.

Is there a better way to do this? And if not, how would you change the seed so that it varies every time the function is called?

Charles
  • 1,384
  • 11
  • 18
  • 3
    Just don't seed inside the function. Seed once in main before you call the other functions. You don't need to reseed every time. – Carcigenicate Jul 12 '17 at 16:56
  • That worked perfectly, shouldn't the seed stay the same at all times since it is set to a number once it is called? – Linus Johansson Jul 12 '17 at 17:00
  • No. The state of the random generator is automatically advanced after you have it generate a value. Manually seeding only sets the initial state to start generating from. – Carcigenicate Jul 12 '17 at 17:02
  • @LinusJohansson That's the point of a seed! An PRNG generates a *sequence* (not just one) of random numbers based on a seed. Different seed => different sequence of random numbers. – yizzlez Jul 12 '17 at 17:03
  • Why the downvote? It seems like a perfectly fair beginner question about a unique quirk of RNGs. It's well worded and it seems like the OP put in effort to understand the question. Unless you want every new question to be about template gunk.... – yizzlez Jul 12 '17 at 17:08
  • 1
    @yizzlez Not my downvote, but lack of research effort would be my guess. This is not hard to google. – Baum mit Augen Jul 12 '17 at 17:13

0 Answers0