rand() 在单个函数中调用时返回相同的值

2021-12-21 00:00:00 random c++

我是 C++ 新手,对此我很困惑.我需要在主函数中调用这个函数三次,但每次都给我相同的结果,即 pull_1、pull_2、pull_3 是相同的.我需要做什么才能使它们真正随机?

I'm a C++ newbie and I'm stumped on this. I need to call this function in my main function three times but each time it gives me the same result, i.e. pull_1, pull_2, pull_3 are the same. What do I need to do to make them actually random?

string PullOne()
{
    string pick;
    string choices[3] = {"BAR", "7", "cherries"};

    std::srand(time(0));
    pick = choices[(std::rand() % 3)];
    return pick;
}

来自我的主要功能:

string pull_1, pull_2, pull_3;
pull_1 = PullOne();
pull_2 = PullOne();
pull_3 = PullOne();

推荐答案

你不应该在每次调用 rand() 之前调用 srand().调用一次在程序开始的某个位置.

You shouldn't call srand() before each call to rand(). Call it once – somewhere at the start of your program.

问题是您重新启动随机生成器,以便它从同一点开始生成完全相同的伪随机序列.

The problem is you restart the random generator so it starts to produce the very same pseudorandom sequence from the very same point.

相关文章