本文介紹了如何從 rand() 縮小數(shù)字?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
以下代碼每秒輸出一個隨機(jī)數(shù):
The following code outputs a random number each second:
int main ()
{
srand(time(NULL)); // Seeds number generator with execution time.
while (true)
{
int rawRand = rand();
std::cout << rawRand << std::endl;
sleep(1);
}
}
如何縮小這些數(shù)字的大小,使其始終在 0-100 的范圍內(nèi)?
How might I size these numbers down so they're always in the range of 0-100?
推薦答案
如果您使用的是 C++ 并且關(guān)心良好的分布,您可以使用 TR1 C++11
.
If you are using C++ and are concerned about good distribution you can use TR1 C++11 <random>
.
#include <random>
std::random_device rseed;
std::mt19937 rgen(rseed()); // mersenne_twister
std::uniform_int_distribution<int> idist(0,100); // [0,100]
std::cout << idist(rgen) << std::endl;
這篇關(guān)于如何從 rand() 縮小數(shù)字?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!