我尝试着创造一款带有骰子的游戏,我需要在其中添加一些随机数字(游戏邦注:即模拟骰子的边缘)。我知道如何在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次生成相同的随机数。是否有这样的命令?


当前回答

以下是我的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;
}

其他回答

如果你正在使用boost lib,你可以通过以下方式获得一个随机生成器:

#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);
    }
};

可以从这里获得生成随机数的完整随机类代码!

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

就像这样:

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";
}

你可以检查这个链接作为一个例子,我如何使用这样的Randomer类生成随机字符串。如果你愿意,你也可以使用Randomer。

这里有一个解决方案。创建一个返回随机数的函数并放置它 在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;
}

每当你在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++生成随机数的人!

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

srand函数的全部意义是用一个随机种子初始化伪随机数序列。

这意味着如果您在两个不同的应用程序(具有相同的srand/rand实现)中将相同的值传递给srand,那么您将在两个应用程序中获得完全相同的rand()值序列。

但是在您的示例应用程序中,伪随机序列只包含一个元素——从种子生成的伪随机序列的第一个元素等于当前时间,精度为1秒。那么您希望在输出上看到什么?

显然,当您恰好在同一秒运行应用程序时—您使用相同的种子值—因此您的结果当然是相同的(Martin York已经在对该问题的评论中提到过)。

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

修改1 -示例代码:

好的,我明白了。 显然口头描述是不够的(可能是语言障碍或其他什么……:))。

老式的C代码示例,基于问题中使用的相同srand()/rand()/time()函数:

#include <stdlib.h>
#include <time.h>
#include <stdio.h>

int main(void)
{
    unsigned long j;
    srand( (unsigned)time(NULL) );

    for( j = 0; j < 100500; ++j )
    {
        int n;

        /* skip rand() readings that would make n%6 non-uniformly distributed
          (assuming rand() itself is uniformly distributed from 0 to RAND_MAX) */
        while( ( n = rand() ) > RAND_MAX - (RAND_MAX-5)%6 )
        { /* bad value retrieved so get next one */ }

        printf( "%d,\t%d\n", n, n % 6 + 1 );
    }

    return 0;
}

^^^程序单次运行的序列看起来应该是随机的。

请注意,我不建议在产品代码中使用rand/srand函数,原因如下所述,我绝对不建议使用函数时间作为随机种子,原因IMO已经很明显了。这些用于教育目的,有时可以用来说明问题,但对于任何严肃的用途,它们大多是无用的。

修订2 -详细说明:

重要的是要明白,到目前为止,没有C或c++标准特性(库函数或类)最终产生实际随机的数据(即由标准保证实际上是随机的)。解决这个问题的唯一标准特性是std::random_device,不幸的是,它仍然不能保证实际的随机性。

根据应用程序的性质,您应该首先决定是否真的需要真正随机(不可预测)的数据。当你确实需要真正的随机性时,值得注意的是信息安全——例如生成对称密钥、非对称私有密钥、盐值、安全令牌等。

实际上,安全级随机数是一个单独的行业,值得另写一篇文章。(在我的回答中,我简要地提到了这一点。)

在大多数情况下伪随机数生成器是足够的-例如科学模拟或游戏。在某些情况下,甚至需要一致定义的伪随机序列——例如,在游戏中,你可以每次在运行时生成相同的地图,以节省安装包的大小。

最初的问题和重复出现的大量相同/相似的问题(甚至是对它们的许多误导的“答案”)表明,首先重要的是区分随机数和伪随机数,首先理解什么是伪随机数序列,并意识到伪随机数生成器的使用方式与使用真随机数生成器的方式不同。

Intuitively when you request random number - the result returned shouldn't depend on previously returned values and shouldn't depend if anyone requested anything before and shouldn't depend in what moment and by what process and on what computer and from what generator and in what galaxy it was requested. That is what word "random" means after all - being unpredictable and independent of anything - otherwise it is not random anymore, right? With this intuition it is only natural to search the web for some magic spells to cast to get such random number in any possible context.

^^^这种直观的期望在所有涉及伪随机数生成器的情况下都是非常错误和有害的——尽管对真随机数来说是合理的。

虽然“随机数”的有意义的概念存在(某种程度上)-没有“伪随机数”这样的东西。伪随机数发生器实际上产生伪随机数序列。

伪随机序列实际上总是确定的(由它的算法和初始参数预先确定)——也就是说,它实际上没有任何随机的东西。

当专家们谈论PRNG的质量时,他们实际上是在谈论所生成序列(及其显著的子序列)的统计属性。例如,如果你轮流使用两个高质量的prng来组合它们,你可能会产生糟糕的结果序列,尽管它们各自产生了良好的序列(这两个良好的序列可能只是相互关联,因此组合不好)。

具体来说,rand()/srand(s)对函数提供了一个奇异的每进程非线程安全(!)伪随机数序列,由实现定义的算法生成。函数rand()生成范围为[0,RAND_MAX]的值。

引用C11标准(ISO/IEC 9899:2011):

的新序列,srand函数使用参数作为种子 后续调用rand返回的伪随机数。如果 然后用相同的种子值(序列)调用Srand 伪随机数应重复。如果rand在any之前被调用 调用srand后,生成的序列应与 当srand第一次被调用时,种子值为1。

Many people reasonably expect that rand() would produce a sequence of semi-independent uniformly distributed numbers in range 0 to RAND_MAX. Well it most certainly should (otherwise it's useless) but unfortunately not only standard doesn't require that - there is even explicit disclaimer that states "there is no guarantees as to the quality of the random sequence produced". In some historical cases rand/srand implementation was of very bad quality indeed. Even though in modern implementations it is most likely good enough - but the trust is broken and not easy to recover. Besides its non-thread-safe nature makes its safe usage in multi-threaded applications tricky and limited (still possible - you may just use them from one dedicated thread).

New class template std::mersenne_twister_engine<> (and its convenience typedefs - std::mt19937/std::mt19937_64 with good template parameters combination) provides per-object pseudo-random number generator defined in C++11 standard. With the same template parameters and the same initialization parameters different objects will generate exactly the same per-object output sequence on any computer in any application built with C++11 compliant standard library. The advantage of this class is its predictably high quality output sequence and full consistency across implementations.

此外,c++ 11标准中还定义了其他(更简单的)PRNG引擎——std::linear_congruential_engine<>(在一些C标准库实现中,历史上被用作公平质量的srand/rand算法)和std::subtract_with_carry_engine<>。它们还生成完全定义的依赖参数的每个对象输出序列。

现代c++ 11例子替换了上面过时的C代码:

#include <iostream>
#include <chrono>
#include <random>

int main()
{
    std::random_device rd;
    // seed value is designed specifically to make initialization
    // parameters of std::mt19937 (instance of std::mersenne_twister_engine<>)
    // different across executions of application
    std::mt19937::result_type seed = rd() ^ (
            (std::mt19937::result_type)
            std::chrono::duration_cast<std::chrono::seconds>(
                std::chrono::system_clock::now().time_since_epoch()
                ).count() +
            (std::mt19937::result_type)
            std::chrono::duration_cast<std::chrono::microseconds>(
                std::chrono::high_resolution_clock::now().time_since_epoch()
                ).count() );

    std::mt19937 gen(seed);

    for( unsigned long j = 0; j < 100500; ++j )
    /* ^^^Yes. Generating single pseudo-random number makes no sense
       even if you use std::mersenne_twister_engine instead of rand()
       and even when your seed quality is much better than time(NULL) */    
    {
        std::mt19937::result_type n;
        // reject readings that would make n%6 non-uniformly distributed
        while( ( n = gen() ) > std::mt19937::max() -
                                    ( std::mt19937::max() - 5 )%6 )
        { /* bad value retrieved so get next one */ }

        std::cout << n << '\t' << n % 6 + 1 << '\n';
    }

    return 0;
}

使用std::uniform_int_distribution<>的前面代码的版本

#include <iostream>
#include <chrono>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937::result_type seed = rd() ^ (
            (std::mt19937::result_type)
            std::chrono::duration_cast<std::chrono::seconds>(
                std::chrono::system_clock::now().time_since_epoch()
                ).count() +
            (std::mt19937::result_type)
            std::chrono::duration_cast<std::chrono::microseconds>(
                std::chrono::high_resolution_clock::now().time_since_epoch()
                ).count() );

    std::mt19937 gen(seed);
    std::uniform_int_distribution<unsigned> distrib(1, 6);

    for( unsigned long j = 0; j < 100500; ++j )
    {
        std::cout << distrib(gen) << ' ';
    }

    std::cout << '\n';
    return 0;
}