本文介紹了每次運行程序時都是相同的隨機數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我每次運行游戲時輸出的隨機數都以相同的順序輸出.為什么會發(fā)生這種情況?
My random numbers that output, output in the same sequence every time I run my game. Why is this happening?
我有
#include <cstdlib>
并使用它來生成隨機數
randomDiceRollComputer = 1 + rand() % 6;
推薦答案
你需要為你的隨機數生成器做種子:
You need to seed your random number generator:
試著把它放在程序的開頭:
Try putting this at the beginning of the program:
srand ( time(NULL) );
請注意,您需要#include
.
這里的想法是在每次啟動程序時為 RNG 設置不同的編號.通過使用時間作為種子,每次啟動程序時您都會得到不同的數字.
The idea here is to seed the RNG with a different number each time you launch the program. By using time as the seed, you get a different number each time you launch the program.
這篇關于每次運行程序時都是相同的隨機數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯(lián)網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯(lián)系我們刪除處理,感謝您的支持!