我尝试着创造一款带有骰子的游戏,我需要在其中添加一些随机数字(游戏邦注:即模拟骰子的边缘)。我知道如何在1到6之间

#include <cstdlib> 
#include <ctime> 
#include <iostream>

using namespace std;

int main() 
{ 
    srand((unsigned)time(0)); 
    int i;
    i = (rand()%6)+1; 
    cout << i << "\n"; 
}

并不是很好地工作,因为当我运行程序几次,这是我得到的输出:

6
1
1
1
1
1
2
2
2
2
5
2

所以我想要一个每次生成不同随机数的命令,而不是连续5次生成相同的随机数。是否有这样的命令?


当前回答

为每个RUN文件随机

size_t randomGenerator(size_t min, size_t max) {
    std::mt19937 rng;
    rng.seed(std::random_device()());
    //rng.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
    std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);

    return dist(rng);
}

其他回答

以下是我的5美分:

// System includes
#include <iostream>
#include <algorithm>
#include <chrono>
#include <random>

// Application includes

// Namespace
using namespace std;

// Constants
#define A_UNUSED(inVariable) (void)inVariable;


int main(int inCounter, char* inArguments[]) {

    A_UNUSED(inCounter);
    A_UNUSED(inArguments);

    std::random_device oRandomDevice;
    mt19937_64 oNumber;
    std::mt19937_64::result_type oSeed;
    std::mt19937_64::result_type oValue1;
    std::mt19937_64::result_type oValue2;

    for (int i = 0; i < 20; i++) {

        oValue1 = (std::mt19937_64::result_type) std::chrono::duration_cast<std::chrono::seconds>(
            std::chrono::system_clock::now().time_since_epoch()
        ).count();
        oValue2 = (std::mt19937_64::result_type) std::chrono::duration_cast<std::chrono::microseconds>(
            std::chrono::system_clock::now().time_since_epoch()
        ).count();
        oSeed = oRandomDevice() ^ (oValue1 + oValue2);
        oNumber.seed(oSeed);

        cout << "oNumber: " << oNumber << "\n";
        cout << "oNumber.default_seed: " << oNumber.default_seed << "\n";
        cout << "oNumber.initialization_multiplier: " << oNumber.initialization_multiplier << "\n";
        cout << "oNumber.mask_bits: " << oNumber.mask_bits << "\n";
        cout << "oNumber.max(): " << oNumber.max() << "\n";
        cout << "oNumber.min(): " << oNumber.min() << "\n";
        cout << "oNumber.shift_size: " << oNumber.shift_size << "\n";
        cout << "oNumber.state_size: " << oNumber.state_size << "\n";
        cout << "oNumber.tempering_b: " << oNumber.tempering_b << "\n";
        cout << "oNumber.tempering_c: " << oNumber.tempering_c << "\n";
        cout << "oNumber.tempering_d: " << oNumber.tempering_d << "\n";
        cout << "oNumber.tempering_l: " << oNumber.tempering_l << "\n";
        cout << "oNumber.tempering_s: " << oNumber.tempering_s << "\n";
        cout << "oNumber.tempering_t: " << oNumber.tempering_t << "\n";
        cout << "oNumber.tempering_u: " << oNumber.tempering_u << "\n";
        cout << "oNumber.word_size: " << oNumber.word_size << "\n";
        cout << "oNumber.xor_mask: " << oNumber.xor_mask << "\n";
        cout << "oNumber._Max: " << oNumber._Max << "\n";
        cout << "oNumber._Min: " << oNumber._Min << "\n";
    }

    cout << "Random v2" << endl;
    return 0;
}

每当你在c++编程语言中做一个基本的随机数生成的web搜索时,这个问题通常是第一个跳出来的!我希望能够更好地阐明c++中伪随机数生成的概念,以便将来在web上不可避免地搜索相同的问题!

最基本的

伪随机数生成涉及利用确定性算法生成性质近似于随机数的数字序列的过程。我之所以说近似,是因为真正的随机性在数学和计算机科学中是一个相当难以捉摸的谜。因此,为什么术语伪随机被用来更学究的正确!

在真正使用PRNG(即伪随机数生成器)之前,必须为算法提供一个初始值,通常也称为种子。然而,在使用算法本身之前,种子必须只设置一次!

/// Proper way!
seed( 1234 ) /// Seed set only once...
for( x in range( 0, 10) ):
  PRNG( seed ) /// Will work as expected

/// Wrong way!
for( x in rang( 0, 10 ) ):
  seed( 1234 ) /// Seed reset for ten iterations!
  PRNG( seed ) /// Output will be the same...

因此,如果您想要一个好的数字序列,那么您必须为PRNG提供一个充足的种子!

旧的C方式

c++的向后兼容标准库使用了cstdlib头文件中所谓的线性同余生成器!这个PRNG通过一个不连续分段函数来实现功能,该函数利用了模算术,即一个喜欢使用模运算符“%”的快速算法。以下是这个PRNG的常用用法,针对@ predictable最初提出的问题:

#include <iostream>
#include <cstdlib>
#include <ctime>

int main( void )
{
  int low_dist  = 1;
  int high_dist = 6;
  std::srand( ( unsigned int )std::time( nullptr ) );
  for( int repetition = 0; repetition < 10; ++repetition )
    std::cout << low_dist + std::rand() % ( high_dist - low_dist ) << std::endl;
  return 0;
}

C的PRNG的常见用法包含了一大堆问题,例如:

The overall interface of std::rand() isn't very intuitive for the proper generation of pseudo-random numbers between a given range, e.g., producing numbers between [1, 6] the way @Predictability wanted. The common usage of std::rand() eliminates the possibility of a uniform distribution of pseudo-random numbers, because of the Pigeonhole Principle. The common way std::rand() gets seeded through std::srand( ( unsigned int )std::time( nullptr ) ) technically isn't correct, because time_t is considered to be a restricted type. Therefore, the conversion from time_t to unsigned int is not guaranteed!

有关使用C的PRNG的总体问题以及如何规避它们的更详细信息,请参阅using rand() (C/ c++): C标准库的rand()函数的建议!

标准c++方式

自从ISO/IEC 14882:2011标准发布以来,即c++ 11,随机库已经从c++编程语言中分离出来一段时间了。该库配备了多个prng,以及不同的分布类型,如:均匀分布,正态分布,二项分布等。下面的源代码示例演示了随机库的一个非常基本的用法,关于@ predictable的原始问题:

#include <iostream>
#include <cctype>
#include <random>

using u32    = uint_least32_t; 
using engine = std::mt19937;

int main( void )
{
  std::random_device os_seed;
  const u32 seed = os_seed();

  engine generator( seed );
  std::uniform_int_distribution< u32 > distribute( 1, 6 );

  for( int repetition = 0; repetition < 10; ++repetition )
    std::cout << distribute( generator ) << std::endl;
  return 0;
}

32位的Mersenne Twister引擎在上面的例子中使用了整数值的均匀分布。(源代码中的引擎名称听起来很奇怪,因为它的名称来自于它的周期2^19937-1)。该示例还使用std::random_device为引擎提供种子,该引擎从操作系统获取其值(如果您使用的是Linux系统,则std::random_device从/dev/urandom返回一个值)。

请注意,您不必使用std::random_device来为任何引擎播种。您可以使用常量甚至chrono库!你也不必使用32位版本的std::mt19937引擎,还有其他选项!有关随机库功能的更多信息,请参阅cplusplus.com

总而言之,c++程序员不应该再使用std::rand(),不是因为它不好,而是因为当前的标准提供了更好的替代方案,更直接、更可靠。希望这篇文章对你们有帮助,特别是那些最近在网上搜索过c++生成随机数的人!

这段代码产生从n到m的随机数。

int random(int from, int to){
    return rand() % (to - from + 1) + from;
}

例子:

int main(){
    srand(time(0));
    cout << random(0, 99) << "\n";
}

每次生成不同的随机数,而不是连续六次生成相同的随机数。

用例场景

我把“可预测性”的问题比作一袋六块纸,每个纸上写着一个从0到5的值。每当需要一个新的数值时,就会从袋子里抽出一张纸。如果袋子是空的,那么数字被放回袋子。

根据这个,我可以创建一个算法。

算法

一个包通常是一个集合。我选择了bool[](也称为布尔数组,位平面或位图)来扮演袋子的角色。

我选择bool[]的原因是,每一项的索引已经是每张纸的值。如果论文需要在它们上面写任何东西,那么我将使用Dictionary<string, bool>代替它。布尔值用于跟踪数字是否已经绘制。

一个名为RemainingNumberCount的计数器被初始化为5,当选择一个随机数时,计数器会向下计数。这样,我们就不必在每次想要画一个新数字时,都要计算还剩下多少张纸了。

为了选择下一个随机值,我使用for..循环来扫描索引包,并使用一个计数器来计数,当索引为false时,称为NumberOfMoves。

NumberOfMoves用于选择下一个可用号码。NumberOfMoves首先被设置为0到5之间的随机值,因为有0..我们可以通过袋子的5个可行步骤。在下一次迭代中,NumberOfMoves被设置为0到4之间的随机值,因为现在有0..我们可以用4步穿过袋子。在使用这些数字时,可用的数字会减少,因此我们使用rand() % (RemainingNumberCount + 1)来计算NumberOfMoves的下一个值。

当NumberOfMoves计数器为零时,for..循环应该如下所示:

将当前值设置为与..循环的索引。 将包中的所有数字设置为false。 停止for..循环。

Code

上述解决方案的代码如下:

(将以下三个块依次放入主.cpp文件中)

#include "stdafx.h"
#include <ctime> 
#include <iostream>
#include <string>

class RandomBag {
public:
    int Value = -1;

    RandomBag() {
        ResetBag();

    }

    void NextValue() {
        int BagOfNumbersLength = sizeof(BagOfNumbers) / sizeof(*BagOfNumbers);

        int NumberOfMoves = rand() % (RemainingNumberCount + 1);

        for (int i = 0; i < BagOfNumbersLength; i++)            
            if (BagOfNumbers[i] == 0) {
                NumberOfMoves--;

                if (NumberOfMoves == -1)
                {
                    Value = i;

                    BagOfNumbers[i] = 1;

                    break;

                }

            }



        if (RemainingNumberCount == 0) {
            RemainingNumberCount = 5;

            ResetBag();

        }
        else            
            RemainingNumberCount--; 

    }

    std::string ToString() {
        return std::to_string(Value);

    }

private:
    bool BagOfNumbers[6]; 

    int RemainingNumberCount;

    int NumberOfMoves;

    void ResetBag() {
        RemainingNumberCount = 5;

        NumberOfMoves = rand() % 6;

        int BagOfNumbersLength = sizeof(BagOfNumbers) / sizeof(*BagOfNumbers);

        for (int i = 0; i < BagOfNumbersLength; i++)            
            BagOfNumbers[i] = 0;

    }

};

控制台类

我创建这个Console类是因为它可以很容易地重定向输出。

下面的代码中…

Console::WriteLine("The next value is " + randomBag.ToString());

...可以用……

std::cout << "The next value is " + randomBag.ToString() << std::endl; 

...然后这个Console类可以根据需要删除。

class Console {
public:
    static void WriteLine(std::string s) {
        std::cout << s << std::endl;

    }

};

主要方法

用法示例如下:

int main() {
    srand((unsigned)time(0)); // Initialise random seed based on current time

    RandomBag randomBag;

    Console::WriteLine("First set of six...\n");

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    Console::WriteLine("\nSecond set of six...\n");

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    Console::WriteLine("\nThird set of six...\n");

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    Console::WriteLine("\nProcess complete.\n");

    system("pause");

}

示例输出

当我运行程序时,我得到以下输出:

First set of six...

The next value is 2
The next value is 3
The next value is 4
The next value is 5
The next value is 0
The next value is 1

Second set of six...

The next value is 3
The next value is 4
The next value is 2
The next value is 0
The next value is 1
The next value is 5

Third set of six...

The next value is 4
The next value is 5
The next value is 2
The next value is 0
The next value is 3
The next value is 1

Process complete.

Press any key to continue . . .

关闭声明

该程序是使用Visual Studio 2017编写的,我选择使用. net 4.6.1使其成为Visual c++ Windows控制台应用程序项目。

我在这里没有做任何特别的事情,所以代码应该也适用于早期版本的Visual Studio。

为每个RUN文件随机

size_t randomGenerator(size_t min, size_t max) {
    std::mt19937 rng;
    rng.seed(std::random_device()());
    //rng.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
    std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);

    return dist(rng);
}