Thread: return random from its own function

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    51

    return random from its own function

    Hello again,
    I have this program that works fine
    Code:
     #include<stdio.h>
    #include<time.h>
    int main(void)
    {
    	srand(time(NULL));
    	int x,i;
    	for(i=0;i<10;i++)
    	{
    		printf("%d: %d\n", i, rand()%100+1);
    	}
    }
    but when I try to put the random number generator in its own function, it only returns the same number repeatedly
    Code:
    /* returns a random number between 1 and the paramater */
    #include<time.h>
    #include<stdio.h>
    
    int func_rand(int n)
    {
    	srand(time(NULL)); /*rand prototype*/
    	return rand()%n+1;
    }
    any ideas why?

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Because you are continuously calling srand/time which, when called in a loop tend to simply reseed the PRNG with the same value meaning the rand call is effectively reset and returns the same value each time.

    Solution: Only call srand once in your program!
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    51
    thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Compiling C in Visual Studio 2005
    By emanresu in forum C Programming
    Replies: 3
    Last Post: 11-16-2009, 04:25 AM
  3. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  4. doubt in c parser coding
    By akshara.sinha in forum C Programming
    Replies: 4
    Last Post: 12-23-2007, 01:49 PM
  5. opengl program as win API menu item
    By SAMSAM in forum Game Programming
    Replies: 1
    Last Post: 03-03-2003, 07:48 PM