### random number generating

HI,
how i can generate real random number enclosed in specific range such 10-100
real random not pseudo .
and how can i exactly use srand();

thanks,
I don't know about real random numbers.

srand() is used together with rand() to generate pseudo-random numbers. srand() is to seed the random number generator (RNG). Using the same seed will give the same sequence of random numbers from rand() so in most cases you want to use a different seed each time. The time() function is often used as seed because it returns different values each second.
`srand(time(0));`
Only call srand once in your program before the first call to rand(). At the beginning of main is a good place. It is a common mistake to call srand each time rand() is called but that will just give numbers that are less "random".

rand() returns an int between 0 and RAND_MAX, where RAND_MAX is a big constant that depends on the compiler. To limit the range of the random number % operator is often used. If you have not seen it before, search modulo operator or remainder operator to understand how it works. `rand() % 91` will return values between 0 and 90. by adding 10, `rand() % 91 + 10` you get a number in between 10-100.
For "real" (non-deterministic) random numbers, C++ has std::random_device

 ``1234567891011`` ``````#include #include int main() { std::random_device rd; std::uniform_int_distribution<> d(10, 100); for(int n = 0; n < 20; ++n) std::cout << d(rd) << ' '; std::cout << '\n'; }``````

But it's really more productive to just get one non-deterministic value and seed a software pseudo-random generator with it:

 ``123456789101112`` ``````#include #include int main() { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<> d(10, 100); for(int n = 0; n < 20; ++n) std::cout << d(mt) << ' '; std::cout << '\n'; }``````
thanks, Peter and Cubbi.
Topic archived. No new replies allowed.