Problem with rand()

Write here if you have problems with your C source code

Moderator: Board moderators

Post Reply
taj79
Learning poster
Posts: 74
Joined: Sun Jun 09, 2002 11:56 am
Location: India
Contact:

Problem with rand()

Post by taj79 »

Hi,

Code: Select all

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


main()
{
	int i,j;

	for(j=0;j<10;j++)
	{
		i = rand();
		printf("\n%d",i);
	}
}
I am running this in Microsoft Visual C++.
The problem is I am getting same set of values everytime I run ... what should I do to get different sets of value ?
jakabjr
Learning poster
Posts: 56
Joined: Wed Mar 23, 2005 9:21 pm
Location: Timisoara, Romania

Post by jakabjr »

Hi. You must use the srand() function to set the random seed (read more about this in help pages or google). to get random numbers you should use srand(time(NULL)), with #include <time.h>, this will give different numbers for different moments of execution.
You should also read about using higher bits for better randomization.
Understanding a problem in a natural way will lead to a natural solution
Post Reply

Return to “C”