Arshdeep Singh Outarel Arshdeep Singh Outarel - 4 months ago 24
C Question

Random list of numbers

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

int main()
{
int i;
int diceRoll;

for(i=0; i < 20; i++)
{
printf("%d \n", rand());
}

return 0;
}


This is the code I wrote in c (codeblocks) to get random numbers, the problem is I always get the same sequence:
41,18467,6334,26500
etc...

I'm still learning so please try to explain like you're talking with a 8 year old D:

Answer

You get the same sequence each time because the seed for the random number generator isn't set. You need to call srand(time(NULL)) like this:

int main()
{
    srand(time(NULL));
    ....
Comments