Why does rand() zlways return 0?

前端 未结 2 915
后悔当初
后悔当初 2020-11-27 19:45

This seems to be a really strange issue:

This is my code:

#import 

int main (int argc, const char * argv[])
{
    @au         


        
相关标签:
2条回答
  • 2020-11-27 20:30

    Well, this

    int seed;
    for(seed = 1; seed < 10; seed++) {
        srand(seed);
        printf("%4d %16d\n", seed, rand());
    }
    

    prints

       1            16807
       2            33614
       3            50421
       4            67228
       5            84035
       6           100842
       7           117649
       8           134456
       9           151263
    

    which makes me think that rand() = seed * 16807

    Wikipedia article Linear congruential generator confirms that CarbonLib indeed uses Xn+1 = Xn * 16807 to generate random numbers.

    0 讨论(0)
  • 2020-11-27 20:32

    It seems unlikely but running some tests, after an srand the first rand seems always to be divisible by 7, at least in an int sized variable.

    On several runs I got 1303562743, 2119476443, and 2120232758, all of which mod 7 to 0.

    The second rand() works, because it is the second rand(). Throw a rand() before your first rand()... or better yet, use a better random number generator random or arc4rand if available.

    Also see Stack Overflow question Why is (rand() % anything) always 0 in C++?.

    0 讨论(0)
提交回复
热议问题