generating random doubles

Hey guys I was wondering how to generate random doubles between the numbers of 1 and 2, so far i have

double)(rand()%2+1)

but that only generates 1 or 2, not 1.2 1.4 1.7 etc

thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <random>

int main()
{
        std::random_device seed;
        std::mt19937 rnd(seed());
        std::uniform_real_distribution<> d(1, 2);

        for(int n = 0; n < 10; ++n)
                std::cout << d(rnd) << ' ';
        std::cout << '\n';
}


online demo: http://ideone.com/GQc6tf

(you could also divide your rand() by (double)RAND_MAX and add 1, but it may not be suitable, since it only generates one of RAND_MAX values, not every possible double: you'd have to call rand() a few more times for each value and do some math if you need full double precision)
Last edited on
hmm are there any simpler ways than this? i don't think we've covered this in my course
also i should note i need to store the numbers into an array, not just print them, if that makes any difference
Topic archived. No new replies allowed.