两个范围之间的随机数

Random number between two range

本文关键字:之间 随机数 范围 两个      更新时间:2023-10-16

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

int a= rand();

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

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

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

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

使用c++ 11可以做以下事情:

包含随机标头:

#include<random>

定义PRNG和分布:

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

获取随机数

double number = distribution(generator); 

在本页和本页中,您可以找到有关uniform_real_distribution的一些参考。

查看这篇文章,它展示了如何使用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;
}
#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;
}

从随机数中取一个模块,用于定义精度。然后执行类型转换以float并除以模块。

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