Rand() 在每次函数调用时返回相同的值

  • 本文关键字:返回 函数调用 Rand c++
  • 更新时间 :
  • 英文 :


每当我在类文件中调用特定方法时,我都会返回一个随机值,但每次再次调用该方法时,它都会返回相同的值。

例如

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。

问题是在生成器中,还是在以下方法中?

你一直在重新播种它。使用相同的种子(假设您有一台比 1920 年更新的计算机,因此可以在一秒钟内执行您的代码)。别这样。

这意味着您一遍又一遍地重新生成和重新启动相同的伪随机序列。因此,每次调用 rand() 时,您都会不断拉出该序列中相同的第一个值。

在您的程序中仅播种一次

例如,您可以将srand调用放入main

这可能需要大约一秒钟,只要您在新的一秒钟开始时就开始执行。整数逻辑等等。无论什么。

你的问题是,每次调用你的函数时,你都会给随机引擎播种:

int CommuterTrain::getRandNumber(int maximumValue)
{
    srand(unsigned(time(NULL))); // <<< This line causes your problems
    int maximum = maximumValue;
    return rand()%maximum+1;
}

当前time()结果不太可能在调用 getRandNumber() 函数之间发生重大变化。

您应该在函数外部调用一次srand(time(NULL))(例如,在CommuterTrain类构造函数中,甚至最好仅在main()中调用)。

最新更新