【问题标题】:Random number between two range两个范围之间的随机数
【发布时间】:2013-04-11 10:49:05
【问题描述】:

rand() 或 qrand() 函数生成一个随机整数。

int a= rand();

我想得到一个介于 0 和 1 之间的随机数。 我怎样才能完成这项工作?

【问题讨论】:

    标签: c++


    【解决方案1】:

    你可以将一个随机的int生成一个float,然后除以RAND_MAX,像这样:

    float a = rand(); // you can use qrand here
    a /= RAND_MAX;
    

    结果将在 0 到 1 的范围内,包括 0 到 1。

    【讨论】:

    • RAND_MAX 是生成器将返回的最大值,因此范围为 1,包括 1。
    • @PeteBecker 你说得对,它包含两端。谢谢!
    【解决方案2】:

    使用 C++11,您可以执行以下操作:

    包含随机头:

    #include<random>
    

    定义 PRNG 和分布:

    std::default_random_engine generator; 
    std::uniform_real_distribution<double> distribution(0.0,1.0);
    

    获取随机数

    double number = distribution(generator); 
    

    this pagethis page 中,您可以找到一些关于uniform_real_distribution 的参考资料。

    【讨论】:

      【解决方案3】:

      查看this 帖子,它展示了如何将 qrand 用于您的目的,这是一个围绕 rand() 的线程安全包装器。

      #include <QGlobal.h>
      #include <QTime>
      
      int QMyClass::randInt(int low, int high)
      {
         // Random number between low and high
         return qrand() % ((high + 1) - low) + low;
      }
      

      【讨论】:

      • 我喜欢这个答案从第一原理解决解决方案的事实。这些公式很难推理,但实际上最容易实现,无需使用额外的库。
      【解决方案4】:
      #include <iostream>
      #include <ctime>
      using namespace std;
      
      //
      // Generate a random number between 0 and 1
      // return a uniform number in [0,1].
      inline double unifRand()
      {
          return rand() / double(RAND_MAX);
      }
      
      // Reset the random number generator with the system clock.
      inline void seed()
      {
          srand(time(0));
      }
      
      
      int main()
      {
          seed();
          for (int i = 0; i < 20; ++i)
          {
              cout << unifRand() << endl;
          }
          return 0;
      }
      

      【讨论】:

        【解决方案5】:

        从定义精度的随机数中获取一个模块。然后进行类型转换以浮动并除以模块。

        float randNum(){
           int random = rand() % 1000;
           float result = ((float) random) / 1000;
           return result;
        }
        

        【讨论】:

        • 简单、有效的解决方案。一个问题:如果模块(在这种情况下为 1000)不能被 RAND_MAX 整除,那么与该范围内的大数字相比,由此产生的随机数将略微偏向于生成较小的数字。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-31
        • 1970-01-01
        相关资源
        最近更新 更多