简体   繁体   中英

c++ rand() strange behavior

I see a very strange behavior when using rand() in c++. Here is my code.

#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <limits.h>

#define N 10
int main() {
    srand(time(NULL));

    while(true) {
        int i = N * ((double) rand() / (RAND_MAX));
        //std::cout << i << std::endl;  // If there is any code here, everything goes fine.
        if (i == N) {
            std::cout << "i " << i << " should never happen" << std::endl;
        } else {  
            std::cout << ".";
        }
    }
}

Here is the output:

i 10 should never happen
i 10 should never happen
i 10 should never happen
...

It really doesn't make sense to me because I think i will never ever be 10. The strange thing is that it works perfectly fine if I try any of the following:

  • I use debugger and step trace the code, the value of i is random in the watch.
  • I add code like sdt:cout as I shown in the comment of my code.
  • I use (RAND_MAX + 1.0) instead of (RAND_MAX).

My compiler is mingw32-g++.exe (TDM-2 mingw32) 4.4.1.

This really confuses me, could anyone tell me what's going on?

This is to be expected:

The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive (ie, the mathematical range [0, RAND_MAX ]).

man rand(3)

So rand() / RAND_MAX can be 1 because the range is inclusive. Your fix with RAND_MAX + 1 is usually the option that is taken.

That being said, there are better options to generate random numbers in a range that will yield a uniform distribution.

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