Possible Duplicate:
Why do I always get the same sequence of random numbers with rand()?
So yeah, this might seem slightly noobish, but since I'm teaching myself C after becoming reasonable at Java, I've already run into some trouble. I'm trying to use the rand() function in C, but I can only call it once, and when it do, it ALWAYS generates the same random number, which is 41. I'm using Microsoft Visual C++ 2010 Express, and I already set it up so it would compile C code, but the only thing not working is this rand() function. I've tried including some generally used libraries, but nothing works. Here's the code:
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
int main(void)
{
printf("%d", rand()); //Always prints 41
return 0;
}
rand()
gives a random value but you need to seed it first. The problem is that if you execute your code more than once (probably), with the same seedsrand(time(NULL))
, thenrand()
; will give always the same value.Then, the second option is to execute, as Thiruvalluvar says,
srand(time(NULL))
and thenrand()
.The one above will give you 1000 random numbers. Try to execute this code and see what happens:
Hope it helps!
You need a seed before you call rand(). Try calling "
srand (time (NULL))
"You have to seed
rand()
.srand ( time(NULL) );
is usually used to initialise random seed. Otherwise,This because the
rand()
initializes its pseudo-random sequence always from the same point when the execution begins.You have to input a really random seed before using
rand()
to obtain different values. This can be done through functionsrand
that will shift the sequence according to the seed passed .Try with:
You must first initialise the random seed using srand().