-1

I have a class function int ComputerClass::getGuess() that every time it is called should produce a randomized number. In my main function I created 2 functions of the class ComputerClass Computer1,Computer2 and called the class function, however it returns the same number for each call:

cout << Computer1.getGuess()<<endl;
cout << Computer2.getGuess()<<endl;

Below is the class member function

int ComputerClass::getGuess()
{
    //Generate randomn number
    srand(time(NULL));
    generatednumber = rand() % 100 + 1;

    //return computers randomly generated #
    cout <<"--(Computer)Please enter a guess between 1-100: "<< 
    generatednumber<<endl;

    return generatednumber;
}

I'm assuming my issue is the seed value, however I don't know how to set it up so that makes the number random every time it is called.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • Call `srand` once at the beginning of your program. Every time you call it with the same number the next value you get will be the same. – Retired Ninja Dec 17 '17 at 04:45
  • Set it up so `srand()` is only called once in the entire program, not every time `getGuess()` is called (which will cause two calls close together in time to be likely to return the same value, since resolution of `time()` is poor). And look up better alternatives for generating random values, in C++11 and later, – Peter Dec 17 '17 at 04:45

1 Answers1

0

You should only call srand once for the entire program. When you call time(NULL) twice very quickly, it will usually return the same value because time ticks more slowly than your CPU.

After you call srand, each subsequent call to rand will return a different value.

IronMensan
  • 6,761
  • 1
  • 26
  • 35