C++ random numbers

前端 未结 7 1075
生来不讨喜
生来不讨喜 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条回答
  •  猫巷女王i
    2021-01-20 06:40

    Regarding the srand(), one item that I don't think has been explained - for a given seed, you will always get the same random sequence (not just srand(0)). Because the time(0) function is changes every second, it is not likely that the seed will be the same from run to run, which is why it is often used with srand().

    Think of the random number generator as a complicated mathematical expression with a single input. Every time you call it, it uses the previous output as then input to generate the next number. The results are predictable, if your input is 5 and you get 10 one time, you'll get it the next time, too. So unless you want to use the same random sequence every run (sometimes not a bad thing!), you want to set the first input (the seed) to something (somewhat) random, such as the current time.

    Caveat: random number generators internally use a much larger number than the one they output, so the input/output relationship is not usually as straightforward as the '5 gets you 10' in the example. But the idea is the same.

提交回复
热议问题