Reputation:
rand() or qrand() functions generate a random int.
int a= rand();
I want to get an random number between 0 and 1. How I can do this Work?
Upvotes: 5
Views: 4960
Reputation: 726489
You can generate a random int
into a float
, and then divide it by RAND_MAX
, like this:
float a = rand(); // you can use qrand here
a /= RAND_MAX;
The result will be in the range from zero to one, inclusive.
Upvotes: 8
Reputation: 3396
Using C++11 you can do the following:
Include the random header:
#include<random>
Define the PRNG and the distribution:
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0,1.0);
Get the random number
double number = distribution(generator);
In this page and in this page you can find some references about uniform_real_distribution
.
Upvotes: 6
Reputation: 1107
Take a module from the random number which will define the precision. Then do a typecast to float and divide by the module.
float randNum(){
int random = rand() % 1000;
float result = ((float) random) / 1000;
return result;
}
Upvotes: 1
Reputation: 17918
#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;
}
Upvotes: 2
Reputation: 11051
Check this post, it shows how to use qrand for your purpose which is afaik a threadsafe 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;
}
Upvotes: 3