1

i use CCRandom_0_1() to generate a random number, as suggested in the book 'learn-iphone-and-ipad-with-cocos2d' but it seems the function generates the same number.

    int ran1 = ((int) (CCRANDOM_0_1() * 5)) + 1;
    int ran2 = ran1;
    while (ran2 == ran1) {
        ran2 = ((int) (CCRANDOM_0_1() * 5)) + 1;
    }

here is the code where i want to generate 2 different integer from 1 to 5. but the console is always

2011-05-28 14:57:56.699 LetsSpotIt[2443:707] r1: 4.200939 r1: 1.971915

Is there anyway i can seed it according to time(mini second something), or is there any other functions to use?

Please give me example code. I didn't learn c or c++ before. Thank you.

OMGPOP
  • 1,995
  • 8
  • 52
  • 95

2 Answers2

6

If you want different values every time you use the code, then you must seed the random generator. The most popular way is to call srandom(time(NULL)) before using CCRANDOM

cpprulez
  • 896
  • 2
  • 9
  • 21
  • you mean add srandom(time(NULL)) line before every CCRandom function or just add once in the app delegate? – OMGPOP May 28 '11 at 07:15
  • Just once in the delegate or some other place ;) Sorry, should've told you that too... – cpprulez May 28 '11 at 08:34
4

Have you tried arc4random() function? Also look here

Community
  • 1
  • 1
  • nope, but i think they are more or less the same. so i assumed i would encounter the same problem for every random functions – OMGPOP May 28 '11 at 07:17
  • yeah, this function is great. but what if i want to use float or double instead of integer? – OMGPOP May 28 '11 at 07:27
  • Interesting. I googled it and found http://stackoverflow.com/questions/1131101/whats-wrong-with-this-randomize-function and http://iphonedevelopment.blogspot.com/2008/10/random-thoughts-rand-vs-arc4random.html –  May 28 '11 at 07:41
  • yeah, worked great for both int and float. don't need to seed at all. cheers. – OMGPOP May 28 '11 at 08:20
  • (((float) arc4random() / 0xFFFFFFFFu) * (high - low)) + low for random float from 'low' to 'high'; arc4random() % aInt for random int from 0 to aInt - 1; – OMGPOP May 28 '11 at 08:25