如何在C ++中生成随机数?

问题描述 投票:90回答:10

我正在尝试用骰子制作游戏,我需要在其中有随机数字(模拟模具的两侧。我知道如何在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次产生不同的随机数。有没有命令可以做到这一点?

c++ random
10个回答
51
投票

测试应用程序最基本的问题是你调用srand一次,然后调用rand一次并退出。

srand函数的重点是用随机种子初始化伪随机数序列。这意味着如果你在两个不同的应用程序中传递相同的值到srand(使用相同的srand / rand实现),那么你将得到完全相同的rand()值序列。但是你的伪随机序列只包含一个元素 - 你的输出由不同的伪随机序列的第一个元素组成,这些元素以1秒精度的时间播种。那你期望看到什么?当您碰巧在同一秒运行应用程序时,您的结果当然是相同的(正如Martin York在答案评论中已提到的那样)。

实际上你应该调用srand(seed)一次,然后多次调用rand()并分析该序列 - 它应该看起来是随机的。


-1
投票

此代码生成从nm的随机数。

int random(int n, int m){
    return rand() % (m - n + 1) + n;
}

例:

int main(){
    srand(time(0));

    for(int i = 0; i < 10; i++)
        cout << random(0, 99);
}

145
投票

使用模可以将偏差引入随机数,这取决于随机数发生器。 See this question for more info.当然,完全有可能以随机顺序重复数字。

尝试一些C ++ 11功能以便更好地分发:

#include <random>
#include <iostream>

int main()
{
    std::random_device dev;
    std::mt19937 rng(dev());
    std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // distribution in range [1, 6]

    std::cout << dist6(rng) << std::endl;
}

See this question/answer for more info on C++11 random numbers.以上不是唯一的方法,但这是一种方式。


9
投票

如果您使用的是boost库,您可以通过以下方式获得随机生成器:

#include <iostream>
#include <string>

// Used in randomization
#include <ctime>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/variate_generator.hpp>

using namespace std;
using namespace boost;

int current_time_nanoseconds(){
    struct timespec tm;
    clock_gettime(CLOCK_REALTIME, &tm);
    return tm.tv_nsec;
}

int main (int argc, char* argv[]) {
    unsigned int dice_rolls = 12;
    random::mt19937 rng(current_time_nanoseconds());
    random::uniform_int_distribution<> six(1,6);

    for(unsigned int i=0; i<dice_rolls; i++){
        cout << six(rng) << endl;
    }
}

函数current_time_nanoseconds()给出当前时间(以纳秒为单位),用作种子。


这是一个更通用的类,用于获取范围内的随机整数和日期:

#include <iostream>
#include <ctime>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/date_time/gregorian/gregorian.hpp"


using namespace std;
using namespace boost;
using namespace boost::posix_time;
using namespace boost::gregorian;


class Randomizer {
private:
    static const bool debug_mode = false;
    random::mt19937 rng_;

    // The private constructor so that the user can not directly instantiate
    Randomizer() {
        if(debug_mode==true){
            this->rng_ = random::mt19937();
        }else{
            this->rng_ = random::mt19937(current_time_nanoseconds());
        }
    };

    int current_time_nanoseconds(){
        struct timespec tm;
        clock_gettime(CLOCK_REALTIME, &tm);
        return tm.tv_nsec;
    }

    // C++ 03
    // ========
    // Dont forget to declare these two. You want to make sure they
    // are unacceptable otherwise you may accidentally get copies of
    // your singleton appearing.
    Randomizer(Randomizer const&);     // Don't Implement
    void operator=(Randomizer const&); // Don't implement

public:
    static Randomizer& get_instance(){
        // The only instance of the class is created at the first call get_instance ()
        // and will be destroyed only when the program exits
        static Randomizer instance;
        return instance;
    }
    bool method() { return true; };

    int rand(unsigned int floor, unsigned int ceil){
        random::uniform_int_distribution<> rand_ = random::uniform_int_distribution<> (floor,ceil);
        return (rand_(rng_));
    }

    // Is not considering the millisecons
    time_duration rand_time_duration(){
        boost::posix_time::time_duration floor(0, 0, 0, 0);
        boost::posix_time::time_duration ceil(23, 59, 59, 0);
        unsigned int rand_seconds = rand(floor.total_seconds(), ceil.total_seconds());
        return seconds(rand_seconds);
    }


    date rand_date_from_epoch_to_now(){
        date now = second_clock::local_time().date();
        return rand_date_from_epoch_to_ceil(now);
    }

    date rand_date_from_epoch_to_ceil(date ceil_date){
        date epoch = ptime(date(1970,1,1)).date();
        return rand_date_in_interval(epoch, ceil_date);
    }

    date rand_date_in_interval(date floor_date, date ceil_date){
        return rand_ptime_in_interval(ptime(floor_date), ptime(ceil_date)).date();
    }

    ptime rand_ptime_from_epoch_to_now(){
        ptime now = second_clock::local_time();
        return rand_ptime_from_epoch_to_ceil(now);
    }

    ptime rand_ptime_from_epoch_to_ceil(ptime ceil_date){
        ptime epoch = ptime(date(1970,1,1));
        return rand_ptime_in_interval(epoch, ceil_date);
    }

    ptime rand_ptime_in_interval(ptime floor_date, ptime ceil_date){
        time_duration const diff = ceil_date - floor_date;
        long long gap_seconds = diff.total_seconds();
        long long step_seconds = Randomizer::get_instance().rand(0, gap_seconds);
        return floor_date + seconds(step_seconds);
    }
};

7
投票
#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    srand(time(NULL));
    int random_number = std::rand(); // rand() return a number between ​0​ and RAND_MAX
    std::cout << random_number;
    return 0;
}

http://en.cppreference.com/w/cpp/numeric/random/rand


2
投票

Can get full Randomer class code for generating random numbers from here!

如果你需要项目不同部分的随机数,你可以创建一个单独的类Randomer来封装其中的所有random内容。

像这样的东西:

class Randomer {
    // random seed by default
    std::mt19937 gen_;
    std::uniform_int_distribution<size_t> dist_;

public:
    /*  ... some convenient ctors ... */ 

    Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
        : gen_{seed}, dist_{min, max} {
    }

    // if you want predictable numbers
    void SetSeed(unsigned int seed) {
        gen_.seed(seed);
    }

    size_t operator()() {
        return dist_(gen_);
    }
};

这样的课程后来会很方便:

int main() {
    Randomer randomer{0, 10};
    std::cout << randomer() << "\n";
}

您可以检查this link as an example how i use这样的Randomer类来生成随机字符串。如果您愿意,也可以使用Randomer


1
投票

这是一个解决方案。创建一个返回随机数的函数,并将其放在main函数之外,使其成为全局函数。希望这可以帮助

#include <iostream>
#include <cstdlib>
#include <ctime>
int rollDie();
using std::cout;
int main (){
    srand((unsigned)time(0));
    int die1;
    int die2;
    for (int n=10; n>0; n--){
    die1 = rollDie();
    die2 = rollDie();
    cout << die1 << " + " << die2 << " = " << die1 + die2 << "\n";
}
system("pause");
return 0;
}
int rollDie(){
    return (rand()%6)+1;
}

1
投票

随机每个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);
}

1
投票

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

用例场景

我把Predictability的问题比作一包六张纸,每张纸上写着0到5的值。每次需要新值时,从袋子中抽出一张纸。如果包是空的,则将数字放回包中。

...从这里,我可以创建一种算法。

算法

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

我选择bool[]的原因是因为每个项目的索引已经是每张纸的价值。如果论文要求在其上写下任何其他内容,那么我会在其位置使用Dictionary<string, bool>。布尔值用于跟踪数字是否已被绘制。

一个名为RemainingNumberCount的计数器被初始化为5,它被选为随机数倒计时。这使我们不必计算每次我们希望绘制新数字时剩余多少张纸。

为了选择下一个随机值,我使用for..loop扫描索引包,并计算一个计数器,当indexfalse称为NumberOfMoves

NumberOfMoves用于选择下一个可用的号码。 NumberOfMoves首先被设置为05之间的随机值,因为我们可以通过包制作0..5个可用步骤。在下一次迭代中,NumberOfMoves被设置为04之间的随机值,因为现在我们可以通过袋子进行0..4步骤。随着数字的使用,可用的数字减少,所以我们改为使用rand() % (RemainingNumberCount + 1)来计算NumberOfMoves的下一个值。

NumberOfMoves计数器达到零时,for..loop应如下:

  1. 将当前值设置为与for..loop的索引相同。
  2. 将包中的所有数字设置为false
  3. 打破for..loop

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

(将以下三个块一个接一个地放入主.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类,因为它可以轻松地重定向输出。

下面的代码......

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编写的,我选择使用Visual C++ Windows Console Application将其作为.Net 4.6.1项目。

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


-1
投票

这是一个简单的随机发电机,约。在0附近产生正负值的概率相等:

  int getNextRandom(const size_t lim) 
  {
        int nextRand = rand() % lim;
        int nextSign = rand() % lim;
        if (nextSign < lim / 2)
            return -nextRand;
        return nextRand;
  }


   int main()
   {
        srand(time(NULL));
        int r = getNextRandom(100);
        cout << r << endl;
        return 0;
   }
© www.soinside.com 2019 - 2024. All rights reserved.