C++ random numbers

前端 未结 7 1134
生来不讨喜
生来不讨喜 2021-01-20 05:55

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 ca

7条回答
  •  甜味超标
    2021-01-20 06:40

    You add 1, because you want random number 1-10, not 0-9, what will % do without the +1.

    For example, 10 % 10 == 0 and 9 % 10 == 9, so this gives you 0-9.
    Adding +1 will "move" this interval to 1-10-> 10 % 10 + 1 == 1 and 9 % 10 + 1 == 10


    EDIT: Sorry, forgot about you srand question. rand() generates the same sequence of numbers, unless you call srand and "seed" the random number generator with different value, before calling rand(). So, here time(0) seeds the random number generator with the current time, that gives you different value for all the times, you call rand()

提交回复
热议问题