Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

c++ create a random decimal between 0.1 and 10

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]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...