I\'m trying to call a class function using a loop
for (int i = 0; i < Basket.getLemonNum(); i++)
{
lemonWeights[i] = Fruit.generateWeight(fruit, fruitWeig
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.
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';
}