【问题标题】:How can I generate a random number between 5 and 25 in c++ [duplicate]如何在 C++ 中生成 5 到 25 之间的随机数 [重复]
【发布时间】:2012-01-01 09:51:13
【问题描述】:

可能重复:
Generate Random numbers uniformly over entire range
C++ random float

如何在 c++ 中生成 5 到 25 之间的随机数?

#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

void main() {

    int number;
    int randomNum;

    srand(time(NULL));

    randomNum = rand();

}

【问题讨论】:

    标签: c++ random srand


    【解决方案1】:

    执行 rand() % 20 并将其递增 5。

    【讨论】:

    • 即使 OP 的问题非常模糊(“随机”是什么意思?),这个答案至少应该提到结果分布是有偏差的。
    • 首先,rand() 是一个伪随机数生成器,而不是一个真正的随机数生成器,因此首先存在偏差。其次,您正在取一个数字的模,其上限不是 20 的因数(查找 MAX_RAND)。这不能使输出均匀分布。我知道我应该在回答中讨论这个问题,但从问题的质量来看,我认为他并不真正需要真正的 RNG。
    【解决方案2】:

    在 C++11 中:

    #include <random>
    
    std::default_random_engine re;
    re.seed(time(NULL)); // or whatever seed
    std::uniform_int_distribution<int> uni(5, 25); // 5-25 *inclusive*
    
    int randomNum = uni(re);
    

    或者也可以是:

    std::uniform_int_distribution<int> d5(1, 5); // 1-5 inclusive
    int randomNum = d5(re) + d5(re) + d5(re) + d5(re) + d5(re);
    

    这将在同一范围内给出不同的分布。

    【讨论】:

    • +1 请注意,如果您的编译器还不支持 C++11,您也可以使用 boost。
    • @KillianDS:甚至&lt;tr1/random&gt; :-)
    【解决方案3】:

    C++ 方式:

    #include <random>
    
    typedef std::mt19937 rng_type; // pick your favourite (i.e. this one)
    std::uniform_int_distribution<rng_type::result_type> udist(5, 25);
    
    rng_type rng;
    
    int main()
    {
      // seed rng first!
    
      rng_type::result_type random_number = udist(rng);
    }
    

    【讨论】:

      【解决方案4】:
      #include <cstdlib>
      #include <time.h>
      
      using namespace std;
      
      void main() {
      
          int number;
          int randomNum;
      
          srand(time(NULL));
      
          number = rand() % 20;
      cout << (number) << endl;
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-19
        • 1970-01-01
        • 2014-03-19
        • 2012-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多