【发布时间】:2014-02-25 00:17:55
【问题描述】:
每当我调用我的类文件中的特定方法时,我都会返回一个随机值,但每次再次调用该方法时它都会继续返回相同的值。
例如
int CommuterTrain::getRandNumber(int maximumValue)
{
srand(unsigned(time(NULL)));
int maximum = maximumValue;
return rand()%maximum+1;
}
void CommuterTrain::loadRiders()
{
int passengers = getRandNumber(350);
currentRiders += passengers;
if (currentRiders > maxCapacity) {
cout << "The train has reached capacity! \nSome people were left at the station."
<< endl;
currentRiders = maxCapacity;
}
else {
cout<<passengers<<" pax have entered the vessel"<<endl;
}
}
假设生成器产生了 215 人。当我再次调用该方法时,它不会再次随机化,并且每次都以 215 结束。
是生成器的问题,还是下面的方法?
【问题讨论】:
-
只播种一次生成器
-
你为什么每次都播
rand?您应该在程序启动时执行一次。 -
Soooooooooooooooo 很多重复...
-
住手!你不是 Johnny Appleseed 或色情明星!
-
我认为这赢得了被问到最多的问题。
标签: c++