lundi 12 juin 2017

Random Function Returns The Same Number When Called Inside A Loop! C++ [duplicate]

This question already has an answer here:

I wanted to create a separate function inside my ff class to generate a random number and return that number. The function seems to work perfectly when used outside a loop. However, when I put the function inside a loop, it keeps generating the same number even though I am calling the random function each time! What exactly am I doing wrong?!

  //return a random number
  int ff::random_number() const
  {
      srand((unsigned)time(NULL));
      return (rand() % 20 + 1); //in the range of 1 to 20
  }


  //creates an int list of random size and random elements
  int ff::create_random_list()
  {
      list_length = random_number(); //the list size
      list_of_numbers = new int[list_length]; //initilize the list

      for (int i = 0; i < list_length; ++i)
          list_of_numbers[i] = random_number(); //insert a random number

      return 1;
  }

  • Note: I've checked all similar questions that were posted before this question, but nothing answered my question. Just to be clear.



Aucun commentaire:

Enregistrer un commentaire