问题描述
我正在尝试使用循环调用类函数
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] << " ";
}
这进入了水果类的成员函数generateWeight():
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
如您所见,我为srand()做了种子.此外,还包括头文件和.发生了什么事?
As you can see, I did seed srand().Also, the header files and are included.What is going on?
推荐答案
您必须调用 srand()
一次,而在 generateWeight()
的每个条目上都调用它.由于当今的计算机运行速度很快,并且 time()
以秒为单位返回时间,因此大多数情况下会从同一种子重新启动随机数生成器.
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.
这篇关于rand()即使在srand(time(NULL))之后也不会生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!