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;
}
cs-142/generating-random-doubles.txt · Last modified: 2015/05/12 19:03 by cs142ta
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0