Generating random integer values within a range in C

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

   This question already has an answer here:
    * /questions/2509679/how-to-generate-a-random-number-from-within-a-range /questions/2509679/how-to-generate-a-random-number-from-within-a-range 10 answers

Answers

http://c-faq.com/lib/randrange.html http://c-faq.com/lib/randrange.html

http://c-faq.com/lib/notveryrand.html http://c-faq.com/lib/notveryrand.html

example code:

#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
int main ()
{
  int r, i;
  int N = 1,
      M = 12;
  /* initialize random seed: */
  srand (time(NULL));

  /* generate secret number between 1 and 10: */
  for(i=0; i < 10 ; i++){ 
     r = M + rand() / (RAND_MAX / (N - M + 1) + 1);
     printf("
%d", r);
  }
  printf("
") ;
  return EXIT_SUCCESS;
}

http://codepad.org/zfAyc24z http://codepad.org/zfAyc24z

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/15962102/generating-random-integer-values-within-a-range-in-c

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils