Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

objective c - Why does rand() % 7 always return 0?

This seems to be a really strange issue:

This is my code:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    @autoreleasepool {
        srand((unsigned int)time(NULL));
        int newRandomNumber = 0;
        newRandomNumber = rand() % 7;
        NSLog(@"%d", rand() % 7); //This prints out what I expected
        NSLog(@"newRandomNumber = %d", newRandomNumber); // This always prints out 0!
    }
    return 0;
}

If I replace that one line that says

newRandomNumber = rand() % 7

with

newRandomNumber = rand() % 8

everything works perfectly. Why is that the case?

question from:https://stackoverflow.com/questions/7866754/why-does-rand-7-always-return-0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, this

int seed;
for(seed = 1; seed < 10; seed++) {
    srand(seed);
    printf("%4d %16d
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...