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

2023-06-05C/C++开发问题
21

本文介绍了在 C++ 中使用 rand() 函数的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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().

这篇关于在 C++ 中使用 rand() 函数的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6