Thread: Random number

  1. #1
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669

    Unhappy Random number

    Hi!

    For random numbers I use "randomize();" and "random(number);". But if I have this in a loop, then the random number is always the same. Why is that so? Please help.
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Something in my .sig should help... can you guess what it is?

    1) Read the FAQ.
    2) Put randomize outside of your loop.
    3) Read the FAQ.
    4) Better yet, use 'srand()' outside your loop instead.
    5) Read the FAQ.
    6) Call your number generation inside the loop. 'rand()'
    7) Read the FAQ.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Unregistered
    Guest
    Hey GaPe,

    First you need to seed the randomizer. You can use randomize() or do it like this:

    srand((unsigned)time(NULL));

    Remember to only seed the randomiser ONCE - i.e. OUTSIDE of you main program loop.

    Whenever you want to get a random number just use:

    rand() % range;

    where range is the maximum number.

    p.s. I think you will need to include <time.h> to seed the randomizer.

  4. #4
    Unregistered
    Guest
    x=rand() % range;

    wouldn't that give you an answer like

    0 through range -1 ?

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    x=rand() % range;

    wouldn't that give you an answer like

    0 through range -1 ?
    Yup. So just add one to it to get 1 to range.

    x = 1 + rand() % range;

    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669
    Thank you guys. It is working now.
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. rapid random number generation problem
    By Newton in forum C Programming
    Replies: 17
    Last Post: 09-19-2008, 02:08 PM
  2. Random number in range generation.
    By hebali in forum C Programming
    Replies: 19
    Last Post: 03-04-2008, 10:46 AM
  3. adding a number to a number
    By bigmac(rexdale) in forum C Programming
    Replies: 11
    Last Post: 10-24-2007, 12:56 PM
  4. random number tutorial
    By 7stud in forum C++ Programming
    Replies: 3
    Last Post: 07-26-2005, 02:41 PM
  5. Random Number Generator
    By Ikurik in forum C++ Programming
    Replies: 16
    Last Post: 08-17-2003, 07:34 PM