Random number between two ranges

Functions

rand () or qrand () generate a random int.

int a= rand();

I want to get a random number from 0 to 1. How can I do this?

+5
source share
5 answers

You can create random intin float, and then split it into RAND_MAX, for example:

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

The result will be in the range from zero to one inclusive.

+8
source

With C ++ 11, you can do the following:

Include random header:

#include<random>

Define PRNG and distribution:

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

Get a random number

double number = distribution(generator); 

In on this page and in on this page you can find links to uniform_real_distribution.

+6
source
#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;
}
+2

Check out this post, it shows how to use qrand for your purpose, which is the afaik thread safety wrapper around 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;
}
+2
source

Take a module from a random number that will determine the accuracy. Then do a cast to float and split the module.

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

All Articles