我是 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.
这篇关于rand() 在单个函数中调用时返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!