-2

I'm trying to call a class function using a loop

for (int i = 0; i < Basket.getLemonNum(); i++)
{
    lemonWeights[i] = Fruit.generateWeight(fruit, fruitWeight);
    cout << lemonWeights[i] << " ";
}  

This goes to the Fruit class to it's member function generateWeight():

   int fruitClass::generateWeight(char fruitN, int& fruitW)
    {
    srand(time(NULL));

    int weight = 0;

    switch (fruitName)
    {
    case 'a':
        weight = rand() % 500 + 100;
        return fruitW = weight;
        break;
    case 'l':
        weight = rand() % 400 + 300; 
        return fruitW = weight;
        break;
    case 'w':
        weight = rand() % 1000 + 800; 
        return fruitW = weight;
        break;
    }
} 



Output:
128 128 128 128

but it's generating the same number all the time, even when I use a different function to call it:

for (int i = 0; i < Basket.getWatermelonNum(); i++)
{
    watermelonWeights[i] = Fruit.generateWeight(fruit, fruitWeight);
    cout << watermelonWeights[i] << " ";

}

Output:
128 128 128

As you can see, I did seed srand(). Also, the header files and are included. What is going on?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
chuakc92
  • 29
  • 7

2 Answers2

5

You must call srand() once, whereas you call it on every entry into generateWeight(). Since nowadays computers are fast and time() returns the time in seconds, this mostly restarts the random number generator from the same seed.

Leon
  • 31,443
  • 4
  • 72
  • 97
0

The problem is that you initialize the pseudo random number generator seed again and again with the same seed (the time which has not changed since the last call since CPUs are very fast today) and, thus, you always get the same "random" number.

Generelly, 1) don't use srand() in a loop and 2) rand() has several defects as it does not generate nicely distributed random numbers (nice video about this rand() considered harmful)

Instead of rand() you should use std::uniform_int_distribution (requires C++11):

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 6);

    for (int n=0; n<10; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}
MrTux
  • 32,350
  • 30
  • 109
  • 146