我是 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模板网!
读取输入文件,最快的方法?read input files, fastest way possible?(读取输入文件,最快的方法?)
在 C++ 中读取格式化输入的最简单方法?The easiest way to read formatted input in C++?(在 C++ 中读取格式化输入的最简单方法?)
从 .txt 文件读取到 C++ 中的二维数组Reading from .txt file into two dimensional array in c++(从 .txt 文件读取到 C++ 中的二维数组)
如何在 C++ 中模拟按键按下How to simulate a key press in C++(如何在 C++ 中模拟按键按下)
为什么在 cin.ignore() 之后没有 getline(cin, var) 读取Why doesn#39;t getline(cin, var) after cin.ignore() read the first character of the string?(为什么在 cin.ignore() 之后没有 getline(cin, var) 读取
scanf 格式输入的 cin 类比是什么?What is the cin analougus of scanf formatted input?(scanf 格式输入的 cin 类比是什么?)