Rand changes value without changing seeds

Run the following program:

#include <cstdlib> using std::rand; #include <iostream> using std::cout; int main() { cout << rand() << ' ' << rand() << ' ' << rand() << '\n'; } 

Due to rand , producing the same values ​​until the seed is changed using srand , this should produce three identical numbers.
eg.

 567 567 567 

However, when I run this program, it gives me three different meanings.
eg.

 6334 18467 41 

When the program (compiled and) starts again, the same three numbers are generated. Should I use srand to change the seed before starting to get different results from rand ? Is this just my compiler / implementation trying to do me a favor?

OS: Windows XP
Compiler: GCC 4.6.2
Libraries: MinGW

EDIT: Trying to use srand , I found that this is the result from seed 1 (which I assume is made by default).

+6
source share
2 answers

Each call to rand() always generates a different random number.

A seed actually determines the sequence of random numbers generated. Using another seed, you will get 3 more random numbers, but you will always get these 3 numbers for a given seed.

If you want to have the same number several times, just call rand() once and save it in a variable.

+4
source

A call to rand() deliberately creates a different random number several times each time it is called.

If your program calls srand() with a different value for each run, the sequence will be the same for each run.

You can use srand() over time so that the whole sequence is different every time. You can also call srand() with the known reset value sequence - useful for testing.

See the documentation for rand () and srand () .

+4
source

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


All Articles