Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      rand

      From cppreference.com
      <c‎ |numeric‎ |random
       
       
       
       
      Defined in header<stdlib.h>
      int rand();

      Returns a pseudo-random integer value between0 andRAND_MAX (0 andRAND_MAX included).

      srand() seeds the pseudo-random number generator used byrand().Ifrand() is used before any calls tosrand(),rand() behaves as if it was seeded withsrand(1).Each timerand() is seeded withsrand(), it must produce the same sequence of values.

      rand() is not guaranteed to be thread-safe.

      Contents

      [edit]Parameters

      (none)

      [edit]Return value

      Pseudo-random integer value between0 andRAND_MAX, inclusive.

      [edit]Notes

      There are no guarantees as to the quality of the random sequence produced.In the past, some implementations ofrand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between1 and0 between calls).rand() is not recommended for serious random-number generation needs, like cryptography.

      POSIX requires that the period of the pseudo-random number generator used byrand be at least232
      .

      POSIX offered a thread-safe version of rand calledrand_r, which is obsolete in favor of thedrand48 family of functions.

      [edit]Example

      Run this code
      #include <stdio.h>#include <stdlib.h>#include <time.h> int main(void){srand(time(NULL));// use current time as seed for random generatorint random_variable= rand();printf("Random value on [0,%d]: %d\n",RAND_MAX, random_variable); // roll a 6-sided die 20 timesfor(int n=0; n!=20;++n){int x=7;while(x>6)             x=1+ rand()/((RAND_MAX+ 1u)/6);// Note: 1+rand()%6 is biasedprintf("%d ",  x);}}

      Possible output:

      Random value on [0,2147483647]: 4487495743 1 3 1 4 2 2 1 3 6 4 4 3 1 6 2 3 2 6 1

      [edit]References

      • C17 standard (ISO/IEC 9899:2018):
      • 7.22.2.1 The rand function (p: 252)
      • C11 standard (ISO/IEC 9899:2011):
      • 7.22.2.1 The rand function (p: 346)
      • C99 standard (ISO/IEC 9899:1999):
      • 7.20.2.1 The rand function (p: 312)
      • C89/C90 standard (ISO/IEC 9899:1990):
      • 4.10.2.1 The rand function

      [edit]See also

      seeds pseudo-random number generator
      (function)[edit]
      maximum possible value generated byrand()
      (macro constant)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=c/numeric/random/rand&oldid=140569"

      [8]ページ先頭

      ©2009-2025 Movatter.jp