Generate Random Double

Problem

• Unordered List Itemrand() generates a random integer between 0 and the maximum value that an integer variable can have. But what if we want a random double?

Solution

#include <iostream>
#include <ctime>

using namespace std;

const int MIN_RAND_NUM = 0;
const int MAX_RAND_NUM = 100;

int main()
{
srand(time(0)); // we want real random, not pseudo-random

// THIS IS HOW YOU CALCULATE A RANDOM DOUBLE BETWEEN 2 USER-DEFINED VARIABLES "MIN_RAND_NUM" and "MAX_RAND_NUM")
// Note that RAND_MAX here is NOT user-defined, but is a constant equal to the max integer value;
double random_double_between_0_1 = rand() * 1.0 / RAND_MAX;

double random_double = (random_double_between_0_1*(MAX_RAND_NUM - MIN_RAND_NUM)) + MIN_RAND_NUM;

cout << "My random double is " << random_double << endl;
}