Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with rand() in C [duplicate]

Tags:

c

random

gcc

Possible Duplicate:
why do i always get the same sequence of random numbers with rand() ?

This is my file so far:

#include <stdio.h>

int main(void) {
    int y;
    y = generateRandomNumber();
    printf("\nThe number is: %d\n", y);
    return 0;
}

int generateRandomNumber(void) {
    int x;
    x = rand();
    return x;
}

My problem is rand() ALWAYS returns 41. I am using gcc on win... not sure what to do here.

EDIT: Using time to generate a random number won't work. It provides me a number (12000ish) and every time I call it is just a little higher (about +3 per second). This isn't the randomness I need. What do I do?

like image 224
akway Avatar asked Nov 28 '22 19:11

akway


2 Answers

you need to provide it a seed.

From the internet -

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

int main(void)
{
  int i, stime;
  long ltime;

  /* get the current calendar time */
  ltime = time(NULL);
  stime = (unsigned) ltime/2;
  srand(stime);

  for(i=0; i<10; i++) printf("%d ", rand());

  return 0;
}
like image 130
Steve Avatar answered Dec 16 '22 22:12

Steve


Standard trick is:

srand(time(0));  // Initialize random number generator.

NOTE: that function is srand, not rand.

Do this once in your main function. After that, only call rand to get numbers.

Depending on the implementation, it can also help to get and discard a few results from rand, to allow the sequence to diverge from the seed value.

like image 33
Daniel Earwicker Avatar answered Dec 16 '22 23:12

Daniel Earwicker