Thread: Need help generating random numbers

  1. #1
    Registered User
    Join Date
    Sep 2007
    Location
    Dunedin, New Zealand
    Posts
    2

    Need help generating random numbers

    Hey all! Teaching myself C and I'm trying to understand how random numbers work...

    I'm trying to make a simple function to generate a single random integer (<= maxnum) that is different every time its called.

    Everybody i've asked so far has sent me through pages and pages of information on pseudo-random numbers which my young brain just cant quite handle yet.

    I've been told to use srand(time(NULL)) to seed, but does that not just use the same number every time? Due to 'time(NULL)' being the system time when the program was RUN?

    Code:
    int getrandnum(int maxnum)
    {
    	srand(time(NULL));
    	return rand() &#37; maxnum + 1;
    }
    Any help much appreciated!

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Don't call srand in your random number function. Call it only once in the program, before the first call to rand.

    http://faq.cprogramming.com/cgi-bin/...&id=1043284385
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Sep 2007
    Location
    Dunedin, New Zealand
    Posts
    2
    Oh brilliant stuff friend - I think nobody I've asked really knew how limited my C knowledge was lol Thanks a heap! - especially for that link!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. questions....so many questions about random numbers....
    By face_master in forum C++ Programming
    Replies: 2
    Last Post: 07-30-2009, 08:47 AM
  2. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  3. Criteria based random numbers
    By alkisclio in forum C++ Programming
    Replies: 6
    Last Post: 09-14-2006, 12:29 PM
  4. Random Number Generating
    By K.n.i.g.h.t in forum C Programming
    Replies: 9
    Last Post: 01-30-2005, 02:16 PM
  5. Another brain block... Random Numbers
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 01-23-2005, 05:51 PM