在 C++ 中生成随机数的最佳方法是什么?

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

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

问题描述

生成随机数的最佳方法是什么?

What is the best way to generate random numbers?

推荐答案

当且仅当:

  • 您不是在寻找完美的一致性"或

  • 您没有 C++11 支持,甚至没有 TR1(因此您别无选择)

  • 那么您可能会考虑使用以下 C 风格的解决方案,其中(为了这个社区的声誉~请参阅 rand() 被认为有害) 以删除线字体书写:

    then you might consider using the following C-style solution, which (for the sake of the reputation of this community ~ see rand() Considered Harmful) is written in strike-through font:

    这是一个简单的 C 风格的函数,它从 minmax 的区间生成随机数,包括.这些数字似乎非常接近均匀分布.

    Here's the simple C-style function that generates random number from the interval from min to max, inclusive. Those numbers seem to be very close to being uniformly distributed.

    int irand(int min, int max) {
        return ((double)rand() / ((double)RAND_MAX + 1.0)) * (max - min + 1) + min;
    }
    

    并且在使用之前不要忘记调用srand:

    int occurences[8] = {0};
    
    srand(time(0));
    for (int i = 0; i < 100000; ++i)
        ++occurences[irand(1,7)];
    
    for (int i = 1; i <= 7; ++i)
        printf("%d ", occurences[i]);
    

    输出:14253 14481 14210 14029 14289 14503 14235

    还可以看看:
    生成范围内的随机数?
    在整个范围内均匀生成随机数
    找些时间,至少观看上述 视频的前 11 分钟

    使用 只是就像 Kerrek SB 已经指出的那样.

    use <random> just like it was pointed out by Kerrek SB already.

    这篇关于在 C++ 中生成随机数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

    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