why is it when i call srand() at 2 very different points it cause numbers to not be random? Once i remove one of them it goes back to normal.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
It depends on how you call it. The purpose of
srand()
is to seed the pseudo-random number generator used byrand()
. So when you callsrand(i)
, it will initialiserand()
to a fixed sequence which depends oni
. So when you re-seed with the same seed, you start getting the same sequence.The most common use case is to seed the generator just once, and with a suitable "random" value (such as the idiomatic
time(NULL)
). Thisguaranteesmakes it likely that you'll get different sequences of pseudo-random numbers in different program executions.However, occasionally you might want to make the pseudo-random sequence "replayable." Imagine you're testing several sorting algorithms on random data. To get fair comparisons, you should test each algorithm on the exact same data - so you'll re-seed the generator with the same seed before each run.
In other words: if you want the numbers simply pseudo-random, seed once, and with a value as random as possible. If you want some control & replayability, seed as necessary.
You may read about pseudo random numbers generators, standard library srand-rand functions are implementation of one of them. The core idea is that pseudo random generator is initialized with the special number - seed. srand() is used to set seed. For every seed pseudo random generator generate exactly the same sequence of numbers ever. By using different seeds you'll get different sequences of numbers. So if you want to get different random numbers everytime you start you program, you need everytime to set new seed. The one of simpliest way to do this is to use time for seed.
Are you initializing the srand? You have to initialize it in the beginning of you function/code like this:
It should work :)
http://www.cplusplus.com/reference/cstdlib/srand/
http://en.cppreference.com/w/cpp/numeric/random/srand