C ++ random numbers

Next: http://www.fredosaurus.com/notes-cpp/misc/random.html

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

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

Why are we adding 1? Can you just explain how this process works?

And as for the initialization of the random number generator, he mentioned the following:

srand(time(0));

Can you explain this process? And what happens if we do not initialize at all?

Thank.

+3
source share
7 answers

You add 1 because you need a random number of 1-10, not 0-9, which will be %without +1.

, 10 % 10 == 0 9 % 10 == 9, 0-9.
+1 "" 1-10- > 10 % 10 + 1 == 1 9 % 10 + 1 == 10


: , srand . rand() , srand "" , rand(). , time(0) , , rand()

+11

rand() int [0, RAND_MAX]. rand() % 10 int [0,9], x k k-1. 1 [1,10].

( rand() % k . , .. RNG Boost.)

srand(time(0)) , . t t + 1s, , . , , , . , C . , , , rand() .

(, , RNG. Linux BSD /dev/random, "" . , .)

+9
  • "modulo", . rand() , rand() % 10 - 0 9. 1, 1 10

  • , . srand(time(0)) "" , . , , , -, , , .

+6

1?

10, 0-9. , , 1.

+4

random without ++ 1 0 9, C, 0 n, . 0, 1-10 (1).

+3

. srand (time (0)), , .

, , , .

, , , srand (0) , . , (0), . .

+2

srand(), , , , , - , ( srand (0)). time (0) , , run to run, srand().

. , , , . , 5, 10 , . , ( !), () - () , .

: , , , / , "5 10" . .

+1

Source: https://habr.com/ru/post/1789715/


All Articles