Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::srand

      From cppreference.com
      <cpp‎ |numeric‎ |random
       
       
       
      Pseudo-random number generation
       
      Defined in header<cstdlib>
      void srand(unsigned seed);

      Seeds the pseudo-random number generator used bystd::rand() with the valueseed.

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

      Each timestd::rand() 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(), at 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 tostd::time(0) as the seed.However,std::time returns astd::time_t value, andstd::time_t is not guaranteed to be an integral type.In practice, though, every major implementation definesstd::time_t to be an integral type, and this is also what POSIX requires.

      [edit]Example

      Run this code
      #include <cstdlib>#include <ctime>#include <iostream> int main(){    std::srand(std::time(0));// use current time as seed for random generatorstd::cout<<"Random value on [0, "<<RAND_MAX<<"]: "<<std::rand()<<'\n';}

      Possible output:

      Random value on [0, 2147483647]: 1373858591

      [edit]See also

      generates a pseudo-random number
      (function)[edit]
      maximum possible value generated bystd::rand
      (macro constant)[edit]
      reseeds the per-thread random engine
      (function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/numeric/random/srand&oldid=151436"

      [8]ページ先頭

      ©2009-2025 Movatter.jp