Thread: New Random # in less than 1 sec...?

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    9

    Question New Random # in less than 1 sec...?

    I read the FAQ and several posts, but can anyone tell me how to generate a random number in less than 1 second? I'm making a game where I need random numbers calculated in less than 1 second and it seems that with Srand(time(NULL)), Randomize(); and rand()%#, it can only get a random number every second. When determining how hard you hit is based on random values and other stats, it sucks getting the same values if you attack twice in less than 1 second and so forth.. Also running into enemies is determined randomly and doing it every second doesn't work cuz you move at least 10 spaces before it determines another number. Anyone help?

  2. #2
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    You only need to call srand() once, and not everytime you need a random number. If this doesn't help post your code.

  3. #3
    Fingerstyle Guitarist taylorguitarman's Avatar
    Join Date
    Aug 2001
    Posts
    564
    you can call rand() as fast as you want and it will give you a different "random" number each time. That's the whole concept behind random numbers.
    this is works just fine.
    Code:
    #include <iostream.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main()
    {
     // this seeds rand()
     // you can put anything you want as a seed but typically you use system time
     srand(time(NULL));
    
     // now make random numbers
     for(int i = 0; i < 20; ++i)
     {
      cout << rand() << endl;
     }
    
     return 0;
    }
    Now unless you have a very slow computer each number should be generated in much less than 1 second and they will statistically be different.
    Note: As in all of the other posts in the past week regarding random numbers (perhaps people should use the search feature?) rand() is a pseudo random generator, which means that it will produce the same sequence with a given seed. Each number will of course be random though.

  4. #4
    Registered User
    Join Date
    Nov 2001
    Posts
    9

    Thumbs up Cool, it worked, thanks :)

    Hey, Thanks Sorensen, that worked, my comp is fast enough and I thank you all for the help but yeah, I was calling the srand() right before it used rand()% and that was in a loop, Thanks guys!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 26
    Last Post: 07-05-2010, 10:43 AM
  2. Lesson #3 - Math
    By oval in forum C# Programming
    Replies: 2
    Last Post: 04-27-2006, 08:16 AM
  3. Another brain block... Random Numbers
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 01-23-2005, 05:51 PM
  4. Replies: 11
    Last Post: 07-16-2002, 11:39 AM
  5. Best way to generate a random double?
    By The V. in forum C Programming
    Replies: 3
    Last Post: 10-16-2001, 04:11 PM