3

How would I do this?

This is my attempt of doing so:

srand (time(NULL));
seed = ((double)rand()) / ((double)RAND_MAX) * 10 + 0.5;

Also what is the way of creating a random integer between 0 and some int x. [0,x]

tmacnadidas
  • 27
  • 1
  • 2
  • 10

3 Answers3

12

The C++11 way:

#include <random>

std::random_device rd;
std::default_random_engine generator(rd()); // rd() provides a random seed
std::uniform_real_distribution<double> distribution(0.1,10);

double number = distribution(generator);

If you only want integers, use this distribution instead:

std::uniform_int_distribution<int> distribution(0, x);

C++11 is really powerful and well-designed in this respect. The generators are separate from the choice of distribution, ranges are taken into account, thread safe, performance is good, and people spent a lot of time to make sure it's all correct. That last part is harder to get right than you think.

Adam
  • 16,808
  • 7
  • 52
  • 98
  • 1
    More information at http://stackoverflow.com/questions/7114043/random-number-generation-in-c11-how-to-generate-how-do-they-work – Silex Oct 29 '13 at 08:05
  • @Silex good link with a longer overview. This talk from GoingNative 2013 is also very interesting and informative: http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful – Adam Oct 29 '13 at 08:17
2
srand (time(NULL));
seed = ((double)rand()) / ((double)RAND_MAX) * 9.9 + 0.1;

To show up to 2 decimal places:

printf("%.2lf\n", seed);

If the x you need is smaller than RAND_MAX, then use

seed = rand() % (x+1);

to generate an integer in [0, x].

timrau
  • 22,578
  • 4
  • 51
  • 64
0
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>

using namespace std;

float r(int fanwei)
{
    srand( (unsigned)time(NULL) ); 
    int nTmp =  rand()%fanwei;
    return (float) nTmp / 10;
}

int main(int argc, const char * argv[])
{
    cout<<r(100)<<endl; 
    return 0;
}
wshcdr
  • 935
  • 2
  • 12
  • 27