我需要在C中產生一個4位的隨機數++C++生成一個4位的隨機數
我用下面的代碼
#include<time.h>
int number;
number=rand()%1000;
srand (time(NULL));
但其不給出了一個總的隨機數
我需要在C中產生一個4位的隨機數++C++生成一個4位的隨機數
我用下面的代碼
#include<time.h>
int number;
number=rand()%1000;
srand (time(NULL));
但其不給出了一個總的隨機數
number = rand() % 9000 + 1000;
有9000個四位數字,對吧?從1000開始到9999. rand()
將返回一個從0到RAND_MAX
的隨機數。 rand() % 9000
將從0到8999,並且rand() % 9000 + 1000;
將從1000到9999。一般來說,當你想從一個隨機數b包括公式是
rand() % (b - a + 1) + a
還要注意的是srand()
應該只有一次,之前的任何rand()
調用。
如果做考慮0的數的999包容是「四位數字」,只是在這種情況下使用rand() % 10000
。我不認爲他們是,但我覆蓋所有的基地,以防萬一。
HTH
記得撥打srand
只有一次。
看看Boost.Random,如果你不喜歡的分佈rand
。
// produces randomness out of thin air
boost::mt19937 rng;
// distribution that maps to 1000..9999
boost::uniform_int<> fourdigits(1000,9999);
// glues randomness with mapping
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(rng, fourdigits);
// simulate rolling a die
int x = die();
用核彈殺死一隻麻雀,我們? :)開玩笑,我喜歡提升,但它可能太多,似乎是一個初學者的操作 – 2010-11-01 07:07:44
雖然公平,它在C++ 0x標準,所以應該是一個標準的分配數字的方式。 – GManNickG 2010-11-01 07:12:28
@GMan:不管它是否標準,對初學者來說都太複雜了。我的觀點是,我們將在標準中使用它,但也許應該保留給中級/高級學習者 – 2010-11-01 07:14:07
您必須種子的隨機數發生器調用rand()
#include<time.h>
srand(time(NULL));
int number = rand() % 10000; // number between 0 and 9999
爲補充公認的答案
srand
之前,沒有關於蘭特)的正確使用方法(和函數srand(一個很不錯的文章)在http://eternallyconfuzzled.com/arts/jsw_art_rand.aspx。 – manneorama 2010-11-01 07:55:05