Why does rand() zlways return 0?

前端 未结 2 930
后悔当初
后悔当初 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.

提交回复
热议问题