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