Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      srand

      From cppreference.com
      <c‎ |numeric‎ |random
       
       
       
       
      Defined in header<stdlib.h>
      void srand(unsigned seed);

      Seeds the pseudo-random number generator used byrand() with the valueseed.

      Ifrand() is used before any calls tosrand(),rand() behaves as if it was seeded withsrand(1).

      Each timerand() is seeded with the sameseed, it must produce the same sequence of values.

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

      Contents

      [edit]Parameters

      seed - the seed value

      [edit]Return value

      (none)

      [edit]Notes

      Generally speaking, the pseudo-random number generator should only be seeded once, before any calls torand(), and the start of the program.It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.

      Standard practice is to use the result of a call totime(0) as the seed.However,time() returns atime_t value, andtime_t is not guaranteed to be an integral type.In practice, though, every major implementation definestime_t to be an integral type, and this is also what POSIX requires.

      [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);}

      Possible output:

      Random value on [0 2147483647]: 1373858591

      [edit]References

      • C17 standard (ISO/IEC 9899:2018):
      • 7.22.2.2 The srand function (p: 252-253)
      • C11 standard (ISO/IEC 9899:2011):
      • 7.22.2.2 The srand function (p: 346-347)
      • C99 standard (ISO/IEC 9899:1999):
      • 7.20.2.2 The srand function (p: 312-313)
      • C89/C90 standard (ISO/IEC 9899:1990):
      • 4.10.2.2 The srand function

      [edit]See also

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

      [8]ページ先頭

      ©2009-2025 Movatter.jp