2009-07-13 92 views
7

我正在做一个书的练习,说要写一个程序,生成psuedorandom数字。我从简单开始。在C++中使用rand()函数的正确方法是什么?

#include "std_lib_facilities.h" 

int randint() 
{ 
    int random = 0; 
    random = rand(); 
    return random; 
} 

int main() 
{ 
    char input = 0; 
    cout << "Press any character and enter to generate a random number." << endl; 
    while (cin >> input) 
    cout << randint() << endl; 
    keep_window_open(); 
} 

我注意到,每次程序运行时,都会有相同的“随机”输出。所以我研究了随机数生成器,并决定尝试通过在randint()中首先包含它来尝试播种。

srand(5355); 

刚刚一遍又一遍的数目相同(我现在觉得愚蠢实现它。)

所以我想我会很聪明和实施这样的种子。

srand(rand()); 

这基本上只是做了作为程序首先没有,但输出的不同组数字(它有道理的,因为由兰特()生成所述第一数总是41)

相同我能想到的唯一的事情,使这个更随机是:

  1. 让用户输入一个号码,设置为种子(这将是很容易实现,但这是不得已而为之) OR
  2. 以某种方式将种子设置为计算机时钟或其他不断变化的数字。

上午我在我的头,我现在应该停下来?选项2难以实施?任何其他想法?

在此先感谢。

回答

27

选项2并不难,在这里你去:

srand(time(NULL)); 

你需要包括time()stdlib.hsrand()time.h

+8

+1,这是标准做法。 – SingleNegationElimination 2009-07-13 00:37:05

+0

如果您处于* nix环境中,您还可以读取/ dev/random;但我同意令牌,这是一个标准的做法,用时间函数设置srand。 – Suroot 2009-07-13 00:42:20

+2

另外,由于您只需调用一次,因此请在主顶部附近调用srand()。不要每次生成新号码时都调用它。 – MahlerFive 2009-07-13 00:52:00

6

这是常见与当前时间的种子的随机数发生器。尝试:

函数srand(时间(NULL));

8

srand()函数只能使用一次:

int randint() 
{ 
    int random = rand(); 
    return random; 
} 

int main() 
{ 
    // To get a unique sequence the random number generator should only be 
    // seeded once during the life of the application. 
    // As long as you don't try and start the application mulitple times a second 
    // you can use time() to get a ever changing seed point that only repeats every 
    // 60 or so years (assuming 32 bit clock). 
    srand(time(NULL)); 
    // Comment the above line out if you need to debug with deterministic behavior. 

    char input = 0; 
    cout << "Press any character and enter to generate a random number." << endl; 

    while (cin >> input) 
    { 
     cout << randint() << endl; 
    } 
    keep_window_open(); 
} 
4

的问题是,如果你不播种发生器将种子本身0(好像srand(0)被称为)。 PRNG被设计为当接种相同时产生相同的序列(由于PNRG不是真的随机的,它们是确定性算法,可能有点因为它对于测试非常有用)。

当你试图

srand(rand()); 

你在做的效果与使用随机数种子吧:

srand(0); 
x = rand(); // x will always be the same. 
srand(x); 

由于FigBug mentioned,采用播种发电机通常是用过的。

0

我认为这些文章的重点是要实现在rand()中的算法,而不是如何有效地对其进行种子处理。产生(伪)随机数不是微不足道的,值得研究不同的技术来产生它们。我不认为简单地使用rand()是作者想到的。

相关问题