在 C++ 中使用 rand() 函数的正确方法是什么?

2021-12-21 00:00:00 random c++

我正在做一个书本练习,内容是编写一个生成伪随机数的程序.我从简单开始.

I'm doing a book exercise that says to write a program that generates psuedorandom numbers. I started off simple with.

#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() 中首先包含它来尝试播种.

I noticed that each time the program was run, there would be the same "random" output. So I looked into random number generators and decided to try seeding by including this first in randint().

    srand(5355);

它一遍又一遍地生成相同的数字(我现在觉得实现它很愚蠢.)

Which just generated the same number over and over (I feel stupid now for implementing it.)

所以我想我会很聪明并像这样实现种子.

So I thought I'd be clever and implement the seed like this.

srand(rand());

这基本上和程序最初所做的一样,但输出了一组不同的数字(这是有道理的,因为 rand() 生成的第一个数字总是 41.)

This basically just did the same as the program did in the first place but outputted a different set of numbers (which makes sense since the first number generated by rand() is always 41.)

我唯一能想到的让这更随机的是:

The only thing I could think of to make this more random is to:

  1. 让用户输入一个数字并将其设置为种子(这很容易实现,但这是最后的手段)或
  2. 以某种方式将种子设置为计算机时钟或其他不断变化的数字.

我是不是脑子进水了,我现在应该停下来吗?选项 2 难以实施吗?还有其他想法吗?

Am I in over my head and should I stop now? Is option 2 difficult to implement? Any other ideas?

提前致谢.

推荐答案

选项 2 并不难,给你:

Option 2 isn't difficult, here you go:

srand(time(NULL));

你需要为 srand() 包含 stdlib.h 和为 time() 包含 time.h代码>.

you'll need to include stdlib.h for srand() and time.h for time().

相关文章