本文介紹了rand() 在單個函數中調用時返回相同的值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我是 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模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!