1

Possible Duplicate:
calling rand() returning non-random results

In my workshop I need to takes 2 different random numbers but I get 2 same random number.

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int random1_6(){
 int k;
 srand(time(0));
 k=((rand()%6)+1);
 return k;
}
int main(void){
 int a,b;
    a=random1_6();
    printf("%d.\n",a);
    b=random1_6();
    printf("%d.\n",b);
return 0;
}

How to get 2 different random number?

Community
  • 1
  • 1
Conan9x1111
  • 13
  • 1
  • 4

4 Answers4

5

A non-cryptographic random number generator (RNG) is not truely random but it generates random-like numbers based on a seed.

What you do is initializing the RNG with the same seed two times, so you get the same results. Seed the RNG just once, e.g. at program start, and you will get random-like different results.

Edit: a code like follows should work:

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

int random1_6(){
  return ((rand() % 6) + 1);
}

int main(void){
  int a,b;
  srand(time(NULL));

  a = random1_6();
  printf("%d.\n",a);

  b=random1_6();
  printf("%d.\n",b);

  return 0;
}
ckruse
  • 9,642
  • 1
  • 25
  • 25
3

Don't do srand(time(0)); on every call. Only call it once.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

You must initialize the random number generator seed with srand() only once : upon each call you are re-initializing the RNG with the same seed since is it most likely that the two subsequent calls to time(0) will return the same timestamp (seconds-level precision), hence rand() will return the same number twice.

If you call srand() only once at the beginning of your program (in the main() entry-point), then every call to rand() will return a different number.

strnk
  • 2,013
  • 18
  • 21
0

You always initialize the random number generator with the same seed, so you'll get the same random sequence, it is pseudo random anyway. Typically you will only want to call srand once in the beginning to initialize the generator.

Also, you only have 6 different possible outcomes, so it is perfectly legitimate to get same number twice, there is 1/6 chance for that.

Jari
  • 2,152
  • 13
  • 20