简体   繁体   中英

Confusion about rand() function in C++

I found out different outputs for the followig cases
Case 1

....
rand();
cout<<a[rand()%4];
....

Case 2

....
//rand();
cout<<a[rand()%4];
......

Without srand() the answer should come same, but it is coming out to be different.

From http://en.cppreference.com/w/cpp/numeric/random/rand

std::srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1). Each time rand() is seeded with srand(), it must produce the same sequence of values on successive calls. Other functions in the standard library may call rand, it is implementation-defined which functions do so. It is implementation-defined whether rand() is thread-safe.

What this means is that rand() produces the same sequence of numbers in case srand with the same seed it set. I think it is the case though that one call to rand() seeds it with seed = 1 and afterwards doesn't set the seed to 1 on succeeding calls. Therfore it will produce a different result. A way to verify this is to explicitly seed with 1 again.

Each call to rand will give you a new pseudo-random number. Calling srand only changes which pseudo-random sequence of numbers you'll get.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM