Thread: SRAND in a range

  1. #1
    Registered User Robert_Ingleby's Avatar
    Join Date
    Oct 2001
    Posts
    57

    SRAND in a range

    How do you use SRAND to generate random numbers in a range of say 9 to 15.

    I have tried all methods, see C Programming notes, but no luck.

    SALEM gave me the answer about 2 months ago, but I cant find the thread anywhere.

  2. #2
    Registered User cody's Avatar
    Join Date
    Sep 2001
    Posts
    86
    Hi

    u'll need functions like:

    - srand()
    - time()
    - rand()

    ...

    Give it a try!
    aloa

    cody

    P.S.: Plz don't crosspost, thnx
    #include "reallife.h"

  3. #3
    Registered User Robert_Ingleby's Avatar
    Join Date
    Oct 2001
    Posts
    57

    I know the header library, but,.....

    I know how to do it from say 1 - 100 but not in a range.

    Here is my code for 1 -100

    #include <stdlib.h>
    #include <stdio.h>
    #include <time.h>

    int main(void)
    {
    int i;
    time_t t;

    srand((unsigned) time(&t));

    for(i=0; i<10; i++)
    printf("%d\n", rand() % 100);
    return 0;
    }

    But how do I do it say numbers from 10 - 25?
    Thankyou

  4. #4
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    there is good info on this in the faq.
    dont crosspost its annoying.

    first seed the random number generator. As it is a pseudorandom number generator the same seed will always produce the same sequence of random numbers. This is normally overcome by seeding with the system time. This only has to be done once.

    srand((unsigned)time(null));

    now to get a range of numbers use rand() coupled with modulus operator...

    for instance range 9-15

    so in general you want to modulus by (highrange-lowrange)+1.
    i.e. 15-9+1=7

    so rand()%7 gives us random numbers in the range 0-6.
    to convert this to range 9-15 just add 9.
    therefore random numbers in range 9-15 can be got like this...
    rand()%7 + 9;

    got it now?
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Overflow and range checking for mul/div
    By Elysia in forum C++ Programming
    Replies: 28
    Last Post: 06-06-2008, 02:09 PM
  2. Random number in range generation.
    By hebali in forum C Programming
    Replies: 19
    Last Post: 03-04-2008, 10:46 AM
  3. Srand () w/ range
    By xsbinary in forum C Programming
    Replies: 9
    Last Post: 10-21-2007, 03:24 PM
  4. Please help to check.
    By nicoleha in forum C Programming
    Replies: 16
    Last Post: 12-07-2005, 03:29 PM
  5. Random Numbers within a range OTHER than 1-X
    By Kaelin in forum C++ Programming
    Replies: 11
    Last Post: 02-16-2005, 11:57 AM