带有 rand 的 Cpp 随机数返回非常相似的数字 [英] Cpp random number with rand returns very similar numbers

查看:46
本文介绍了带有 rand 的 Cpp 随机数返回非常相似的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 rand() 命令生成一个随机数,但每次我都会得到非常相似的数字.这是我的代码:

I'm trying to generate a random number using rand() command, but each time i get very similar numbers. This is my code:

#include <iostream>
#include <time.h>
using namespace std;

int main()
{
    srand(time(0));
    cout << rand();
    return 0;
}

我运行了 5 次,得到的数字是:2176721806218362186221888

I ran it 5 times and the numbers i got are: 21767 21806 21836 21862 21888

如何让数字变得更加不同?

How can i make the numbers be more different?

推荐答案

来自 rand 的文档:

From the documentation of rand:

无法保证生成的随机序列的质量.过去,rand() 的一些实现在产生的序列的随机性、分布和周期方面存在严重缺陷(在一个众所周知的例子中,低位在调用之间简单地在 1 和 0 之间交替).rand() 不推荐用于严重的随机数生成需求.推荐使用C++11的随机数生成工具来代替rand().

There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls). rand() is not recommended for serious random-number generation needs. It is recommended to use C++11's random number generation facilities to replace rand().

它(和我)建议在 .

It (and I) recommend to use the newer c++11 random number generators in <random>.

在您的特定情况下,您似乎想要一个 std::uniform_int_distribution.链接页面上给出的示例是:

In your specific case it seems you want a std::uniform_int_distribution. An example, as given on the linked page is:

std::random_device rd;  //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> distrib(1, RAND_MAX);
std::cout << distrib(gen) << '\n';

这篇关于带有 rand 的 Cpp 随机数返回非常相似的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆