C++ random numbers

2019-02-24 22:44发布

At the following: http://www.fredosaurus.com/notes-cpp/misc/random.html

It mentions that if we want to generate a random number in the range 1-10, we can do the following:

r = (rand() % 10) + 1;

Why do we add 1? Can you just explain how the process works?

And, regarding initializing the random number generator, it mentioned doing the following:

srand(time(0));

Can you explain this process? And, what happens if we don't initialize at all?

Thanks.

标签: c++ random
7条回答
不美不萌又怎样
2楼-- · 2019-02-24 23:31

The modulo part is answered by others. You must initialize with srand(time(0)) because otherwise you will get the same series of random numbers each time your program runs.

As far as I understand it, this is because the generator starts with a certain number and following numbers are calculated based on this starting number.

You can initialise with any number you like, for example for testing you could use srand(0) and get the same numbers as in the last run. To get a fully random series you use time(0) because that initialises with the actual time in seconds Which is random enough for most purposes.

查看更多
登录 后发表回答